You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

934 lines
28 KiB

  1. #ifndef __INC_LIB8TION_H
  2. #define __INC_LIB8TION_H
  3. /*
  4. Fast, efficient 8-bit math functions specifically
  5. designed for high-performance LED programming.
  6. Because of the AVR(Arduino) and ARM assembly language
  7. implementations provided, using these functions often
  8. results in smaller and faster code than the equivalent
  9. program using plain "C" arithmetic and logic.
  10. Included are:
  11. - Saturating unsigned 8-bit add and subtract.
  12. Instead of wrapping around if an overflow occurs,
  13. these routines just 'clamp' the output at a maxumum
  14. of 255, or a minimum of 0. Useful for adding pixel
  15. values. E.g., qadd8( 200, 100) = 255.
  16. qadd8( i, j) == MIN( (i + j), 0xFF )
  17. qsub8( i, j) == MAX( (i - j), 0 )
  18. - Saturating signed 8-bit ("7-bit") add.
  19. qadd7( i, j) == MIN( (i + j), 0x7F)
  20. - Scaling (down) of unsigned 8- and 16- bit values.
  21. Scaledown value is specified in 1/256ths.
  22. scale8( i, sc) == (i * sc) / 256
  23. scale16by8( i, sc) == (i * sc) / 256
  24. Example: scaling a 0-255 value down into a
  25. range from 0-99:
  26. downscaled = scale8( originalnumber, 100);
  27. A special version of scale8 is provided for scaling
  28. LED brightness values, to make sure that they don't
  29. accidentally scale down to total black at low
  30. dimming levels, since that would look wrong:
  31. scale8_video( i, sc) = ((i * sc) / 256) +? 1
  32. Example: reducing an LED brightness by a
  33. dimming factor:
  34. new_bright = scale8_video( orig_bright, dimming);
  35. - Fast 8- and 16- bit unsigned random numbers.
  36. Significantly faster than Arduino random(), but
  37. also somewhat less random. You can add entropy.
  38. random8() == random from 0..255
  39. random8( n) == random from 0..(N-1)
  40. random8( n, m) == random from N..(M-1)
  41. random16() == random from 0..65535
  42. random16( n) == random from 0..(N-1)
  43. random16( n, m) == random from N..(M-1)
  44. random16_set_seed( k) == seed = k
  45. random16_add_entropy( k) == seed += k
  46. - Absolute value of a signed 8-bit value.
  47. abs8( i) == abs( i)
  48. - 8-bit math operations which return 8-bit values.
  49. These are provided mostly for completeness,
  50. not particularly for performance.
  51. mul8( i, j) == (i * j) & 0xFF
  52. add8( i, j) == (i + j) & 0xFF
  53. sub8( i, j) == (i - j) & 0xFF
  54. - Fast 16-bit approximations of sin and cos.
  55. Input angle is a uint16_t from 0-65535.
  56. Output is a signed int16_t from -32767 to 32767.
  57. sin16( x) == sin( (x/32768.0) * pi) * 32767
  58. cos16( x) == cos( (x/32768.0) * pi) * 32767
  59. Accurate to more than 99% in all cases.
  60. - Fast 8-bit approximations of sin and cos.
  61. Input angle is a uint8_t from 0-255.
  62. Output is an UNsigned uint8_t from 0 to 255.
  63. sin8( x) == (sin( (x/128.0) * pi) * 128) + 128
  64. cos8( x) == (cos( (x/128.0) * pi) * 128) + 128
  65. Accurate to within about 2%.
  66. - Fast 8-bit "easing in/out" function.
  67. ease8InOutCubic(x) == 3(x^i) - 2(x^3)
  68. ease8InOutApprox(x) ==
  69. faster, rougher, approximation of cubic easing
  70. ease8InOutQuad(x) == quadratic (vs cubic) easing
  71. - Cubic, Quadratic, and Triangle wave functions.
  72. Input is a uint8_t representing phase withing the wave,
  73. similar to how sin8 takes an angle 'theta'.
  74. Output is a uint8_t representing the amplitude of
  75. the wave at that point.
  76. cubicwave8( x)
  77. quadwave8( x)
  78. triwave8( x)
  79. - Square root for 16-bit integers. About three times
  80. faster and five times smaller than Arduino's built-in
  81. generic 32-bit sqrt routine.
  82. sqrt16( uint16_t x ) == sqrt( x)
  83. - Dimming and brightening functions for 8-bit
  84. light values.
  85. dim8_video( x) == scale8_video( x, x)
  86. dim8_raw( x) == scale8( x, x)
  87. dim8_lin( x) == (x<128) ? ((x+1)/2) : scale8(x,x)
  88. brighten8_video( x) == 255 - dim8_video( 255 - x)
  89. brighten8_raw( x) == 255 - dim8_raw( 255 - x)
  90. brighten8_lin( x) == 255 - dim8_lin( 255 - x)
  91. The dimming functions in particular are suitable
  92. for making LED light output appear more 'linear'.
  93. - Linear interpolation between two values, with the
  94. fraction between them expressed as an 8- or 16-bit
  95. fixed point fraction (fract8 or fract16).
  96. lerp8by8( fromU8, toU8, fract8 )
  97. lerp16by8( fromU16, toU16, fract8 )
  98. lerp15by8( fromS16, toS16, fract8 )
  99. == from + (( to - from ) * fract8) / 256)
  100. lerp16by16( fromU16, toU16, fract16 )
  101. == from + (( to - from ) * fract16) / 65536)
  102. map8( in, rangeStart, rangeEnd)
  103. == map( in, 0, 255, rangeStart, rangeEnd);
  104. - Optimized memmove, memcpy, and memset, that are
  105. faster than standard avr-libc 1.8.
  106. memmove8( dest, src, bytecount)
  107. memcpy8( dest, src, bytecount)
  108. memset8( buf, value, bytecount)
  109. - Beat generators which return sine or sawtooth
  110. waves in a specified number of Beats Per Minute.
  111. Sine wave beat generators can specify a low and
  112. high range for the output. Sawtooth wave beat
  113. generators always range 0-255 or 0-65535.
  114. beatsin8( BPM, low8, high8)
  115. = (sine(beatphase) * (high8-low8)) + low8
  116. beatsin16( BPM, low16, high16)
  117. = (sine(beatphase) * (high16-low16)) + low16
  118. beatsin88( BPM88, low16, high16)
  119. = (sine(beatphase) * (high16-low16)) + low16
  120. beat8( BPM) = 8-bit repeating sawtooth wave
  121. beat16( BPM) = 16-bit repeating sawtooth wave
  122. beat88( BPM88) = 16-bit repeating sawtooth wave
  123. BPM is beats per minute in either simple form
  124. e.g. 120, or Q8.8 fixed-point form.
  125. BPM88 is beats per minute in ONLY Q8.8 fixed-point
  126. form.
  127. Lib8tion is pronounced like 'libation': lie-BAY-shun
  128. */
  129. #include <stdint.h>
  130. #define LIB8STATIC static inline
  131. #define LIB8STATIC_ALWAYS_INLINE static inline
  132. #if !defined(__AVR__)
  133. #include <string.h>
  134. // for memmove, memcpy, and memset if not defined here
  135. #endif
  136. #if defined(__arm__)
  137. #if defined(FASTLED_TEENSY3)
  138. // Can use Cortex M4 DSP instructions
  139. #define QADD8_C 0
  140. #define QADD7_C 0
  141. #define QADD8_ARM_DSP_ASM 1
  142. #define QADD7_ARM_DSP_ASM 1
  143. #else
  144. // Generic ARM
  145. #define QADD8_C 1
  146. #define QADD7_C 1
  147. #endif
  148. #define QSUB8_C 1
  149. #define SCALE8_C 1
  150. #define SCALE16BY8_C 1
  151. #define SCALE16_C 1
  152. #define ABS8_C 1
  153. #define MUL8_C 1
  154. #define QMUL8_C 1
  155. #define ADD8_C 1
  156. #define SUB8_C 1
  157. #define EASE8_C 1
  158. #define AVG8_C 1
  159. #define AVG7_C 1
  160. #define AVG16_C 1
  161. #define AVG15_C 1
  162. #define BLEND8_C 1
  163. #elif defined(__AVR__)
  164. // AVR ATmega and friends Arduino
  165. #define QADD8_C 0
  166. #define QADD7_C 0
  167. #define QSUB8_C 0
  168. #define ABS8_C 0
  169. #define ADD8_C 0
  170. #define SUB8_C 0
  171. #define AVG8_C 0
  172. #define AVG7_C 0
  173. #define AVG16_C 0
  174. #define AVG15_C 0
  175. #define QADD8_AVRASM 1
  176. #define QADD7_AVRASM 1
  177. #define QSUB8_AVRASM 1
  178. #define ABS8_AVRASM 1
  179. #define ADD8_AVRASM 1
  180. #define SUB8_AVRASM 1
  181. #define AVG8_AVRASM 1
  182. #define AVG7_AVRASM 1
  183. #define AVG16_AVRASM 1
  184. #define AVG15_AVRASM 1
  185. // Note: these require hardware MUL instruction
  186. // -- sorry, ATtiny!
  187. #if !defined(LIB8_ATTINY)
  188. #define SCALE8_C 0
  189. #define SCALE16BY8_C 0
  190. #define SCALE16_C 0
  191. #define MUL8_C 0
  192. #define QMUL8_C 0
  193. #define EASE8_C 0
  194. #define BLEND8_C 0
  195. #define SCALE8_AVRASM 1
  196. #define SCALE16BY8_AVRASM 1
  197. #define SCALE16_AVRASM 1
  198. #define MUL8_AVRASM 1
  199. #define QMUL8_AVRASM 1
  200. #define EASE8_AVRASM 1
  201. #define CLEANUP_R1_AVRASM 1
  202. #define BLEND8_AVRASM 1
  203. #else
  204. // On ATtiny, we just use C implementations
  205. #define SCALE8_C 1
  206. #define SCALE16BY8_C 1
  207. #define SCALE16_C 1
  208. #define MUL8_C 1
  209. #define QMUL8_C 1
  210. #define EASE8_C 1
  211. #define BLEND8_C 1
  212. #define SCALE8_AVRASM 0
  213. #define SCALE16BY8_AVRASM 0
  214. #define SCALE16_AVRASM 0
  215. #define MUL8_AVRASM 0
  216. #define QMUL8_AVRASM 0
  217. #define EASE8_AVRASM 0
  218. #define BLEND8_AVRASM 0
  219. #endif
  220. #else
  221. // unspecified architecture, so
  222. // no ASM, everything in C
  223. #define QADD8_C 1
  224. #define QADD7_C 1
  225. #define QSUB8_C 1
  226. #define SCALE8_C 1
  227. #define SCALE16BY8_C 1
  228. #define SCALE16_C 1
  229. #define ABS8_C 1
  230. #define MUL8_C 1
  231. #define QMUL8_C 1
  232. #define ADD8_C 1
  233. #define SUB8_C 1
  234. #define EASE8_C 1
  235. #define AVG8_C 1
  236. #define AVG7_C 1
  237. #define AVG16_C 1
  238. #define AVG15_C 1
  239. #define BLEND8_C 1
  240. #endif
  241. ///@defgroup lib8tion Fast math functions
  242. ///A variety of functions for working with numbers.
  243. ///@{
  244. ///////////////////////////////////////////////////////////////////////
  245. //
  246. // typdefs for fixed-point fractional types.
  247. //
  248. // sfract7 should be interpreted as signed 128ths.
  249. // fract8 should be interpreted as unsigned 256ths.
  250. // sfract15 should be interpreted as signed 32768ths.
  251. // fract16 should be interpreted as unsigned 65536ths.
  252. //
  253. // Example: if a fract8 has the value "64", that should be interpreted
  254. // as 64/256ths, or one-quarter.
  255. //
  256. //
  257. // fract8 range is 0 to 0.99609375
  258. // in steps of 0.00390625
  259. //
  260. // sfract7 range is -0.9921875 to 0.9921875
  261. // in steps of 0.0078125
  262. //
  263. // fract16 range is 0 to 0.99998474121
  264. // in steps of 0.00001525878
  265. //
  266. // sfract15 range is -0.99996948242 to 0.99996948242
  267. // in steps of 0.00003051757
  268. //
  269. /// ANSI unsigned short _Fract. range is 0 to 0.99609375
  270. /// in steps of 0.00390625
  271. typedef uint8_t fract8; ///< ANSI: unsigned short _Fract
  272. /// ANSI: signed short _Fract. range is -0.9921875 to 0.9921875
  273. /// in steps of 0.0078125
  274. typedef int8_t sfract7; ///< ANSI: signed short _Fract
  275. /// ANSI: unsigned _Fract. range is 0 to 0.99998474121
  276. /// in steps of 0.00001525878
  277. typedef uint16_t fract16; ///< ANSI: unsigned _Fract
  278. /// ANSI: signed _Fract. range is -0.99996948242 to 0.99996948242
  279. /// in steps of 0.00003051757
  280. typedef int16_t sfract15; ///< ANSI: signed _Fract
  281. // accumXY types should be interpreted as X bits of integer,
  282. // and Y bits of fraction.
  283. // E.g., accum88 has 8 bits of int, 8 bits of fraction
  284. typedef uint16_t accum88; ///< ANSI: unsigned short _Accum. 8 bits int, 8 bits fraction
  285. typedef int16_t saccum78; ///< ANSI: signed short _Accum. 7 bits int, 8 bits fraction
  286. typedef uint32_t accum1616;///< ANSI: signed _Accum. 16 bits int, 16 bits fraction
  287. typedef int32_t saccum1516;///< ANSI: signed _Accum. 15 bits int, 16 bits fraction
  288. typedef uint16_t accum124; ///< no direct ANSI counterpart. 12 bits int, 4 bits fraction
  289. typedef int32_t saccum114;///< no direct ANSI counterpart. 1 bit int, 14 bits fraction
  290. #include "math8.h"
  291. #include "scale8.h"
  292. #include "random8.h"
  293. #include "trig8.h"
  294. ///////////////////////////////////////////////////////////////////////
  295. ///////////////////////////////////////////////////////////////////////
  296. //
  297. // float-to-fixed and fixed-to-float conversions
  298. //
  299. // Note that anything involving a 'float' on AVR will be slower.
  300. /// sfract15ToFloat: conversion from sfract15 fixed point to
  301. /// IEEE754 32-bit float.
  302. LIB8STATIC float sfract15ToFloat( sfract15 y)
  303. {
  304. return y / 32768.0;
  305. }
  306. /// conversion from IEEE754 float in the range (-1,1)
  307. /// to 16-bit fixed point. Note that the extremes of
  308. /// one and negative one are NOT representable. The
  309. /// representable range is basically
  310. LIB8STATIC sfract15 floatToSfract15( float f)
  311. {
  312. return f * 32768.0;
  313. }
  314. ///////////////////////////////////////////////////////////////////////
  315. //
  316. // memmove8, memcpy8, and memset8:
  317. // alternatives to memmove, memcpy, and memset that are
  318. // faster on AVR than standard avr-libc 1.8
  319. #if defined(__AVR__)
  320. void * memmove8( void * dst, const void * src, uint16_t num );
  321. void * memcpy8 ( void * dst, const void * src, uint16_t num ) __attribute__ ((noinline));
  322. void * memset8 ( void * ptr, uint8_t value, uint16_t num ) __attribute__ ((noinline)) ;
  323. #else
  324. // on non-AVR platforms, these names just call standard libc.
  325. #define memmove8 memmove
  326. #define memcpy8 memcpy
  327. #define memset8 memset
  328. #endif
  329. ///////////////////////////////////////////////////////////////////////
  330. //
  331. // linear interpolation, such as could be used for Perlin noise, etc.
  332. //
  333. // A note on the structure of the lerp functions:
  334. // The cases for b>a and b<=a are handled separately for
  335. // speed: without knowing the relative order of a and b,
  336. // the value (a-b) might be overflow the width of a or b,
  337. // and have to be promoted to a wider, slower type.
  338. // To avoid that, we separate the two cases, and are able
  339. // to do all the math in the same width as the arguments,
  340. // which is much faster and smaller on AVR.
  341. /// linear interpolation between two unsigned 8-bit values,
  342. /// with 8-bit fraction
  343. LIB8STATIC uint8_t lerp8by8( uint8_t a, uint8_t b, fract8 frac)
  344. {
  345. uint8_t result;
  346. if( b > a) {
  347. uint8_t delta = b - a;
  348. uint8_t scaled = scale8( delta, frac);
  349. result = a + scaled;
  350. } else {
  351. uint8_t delta = a - b;
  352. uint8_t scaled = scale8( delta, frac);
  353. result = a - scaled;
  354. }
  355. return result;
  356. }
  357. /// linear interpolation between two unsigned 16-bit values,
  358. /// with 16-bit fraction
  359. LIB8STATIC uint16_t lerp16by16( uint16_t a, uint16_t b, fract16 frac)
  360. {
  361. uint16_t result;
  362. if( b > a ) {
  363. uint16_t delta = b - a;
  364. uint16_t scaled = scale16(delta, frac);
  365. result = a + scaled;
  366. } else {
  367. uint16_t delta = a - b;
  368. uint16_t scaled = scale16( delta, frac);
  369. result = a - scaled;
  370. }
  371. return result;
  372. }
  373. /// linear interpolation between two unsigned 16-bit values,
  374. /// with 8-bit fraction
  375. LIB8STATIC uint16_t lerp16by8( uint16_t a, uint16_t b, fract8 frac)
  376. {
  377. uint16_t result;
  378. if( b > a) {
  379. uint16_t delta = b - a;
  380. uint16_t scaled = scale16by8( delta, frac);
  381. result = a + scaled;
  382. } else {
  383. uint16_t delta = a - b;
  384. uint16_t scaled = scale16by8( delta, frac);
  385. result = a - scaled;
  386. }
  387. return result;
  388. }
  389. /// linear interpolation between two signed 15-bit values,
  390. /// with 8-bit fraction
  391. LIB8STATIC int16_t lerp15by8( int16_t a, int16_t b, fract8 frac)
  392. {
  393. int16_t result;
  394. if( b > a) {
  395. uint16_t delta = b - a;
  396. uint16_t scaled = scale16by8( delta, frac);
  397. result = a + scaled;
  398. } else {
  399. uint16_t delta = a - b;
  400. uint16_t scaled = scale16by8( delta, frac);
  401. result = a - scaled;
  402. }
  403. return result;
  404. }
  405. /// linear interpolation between two signed 15-bit values,
  406. /// with 8-bit fraction
  407. LIB8STATIC int16_t lerp15by16( int16_t a, int16_t b, fract16 frac)
  408. {
  409. int16_t result;
  410. if( b > a) {
  411. uint16_t delta = b - a;
  412. uint16_t scaled = scale16( delta, frac);
  413. result = a + scaled;
  414. } else {
  415. uint16_t delta = a - b;
  416. uint16_t scaled = scale16( delta, frac);
  417. result = a - scaled;
  418. }
  419. return result;
  420. }
  421. /// map8: map from one full-range 8-bit value into a narrower
  422. /// range of 8-bit values, possibly a range of hues.
  423. ///
  424. /// E.g. map myValue into a hue in the range blue..purple..pink..red
  425. /// hue = map8( myValue, HUE_BLUE, HUE_RED);
  426. ///
  427. /// Combines nicely with the waveform functions (like sin8, etc)
  428. /// to produce continuous hue gradients back and forth:
  429. ///
  430. /// hue = map8( sin8( myValue), HUE_BLUE, HUE_RED);
  431. ///
  432. /// Mathematically simiar to lerp8by8, but arguments are more
  433. /// like Arduino's "map"; this function is similar to
  434. ///
  435. /// map( in, 0, 255, rangeStart, rangeEnd)
  436. ///
  437. /// but faster and specifically designed for 8-bit values.
  438. LIB8STATIC uint8_t map8( uint8_t in, uint8_t rangeStart, uint8_t rangeEnd)
  439. {
  440. uint8_t rangeWidth = rangeEnd - rangeStart;
  441. uint8_t out = scale8( in, rangeWidth);
  442. out += rangeStart;
  443. return out;
  444. }
  445. ///////////////////////////////////////////////////////////////////////
  446. //
  447. // easing functions; see http://easings.net
  448. //
  449. /// ease8InOutQuad: 8-bit quadratic ease-in / ease-out function
  450. /// Takes around 13 cycles on AVR
  451. #if EASE8_C == 1
  452. LIB8STATIC uint8_t ease8InOutQuad( uint8_t i)
  453. {
  454. uint8_t j = i;
  455. if( j & 0x80 ) {
  456. j = 255 - j;
  457. }
  458. uint8_t jj = scale8( j, j);
  459. uint8_t jj2 = jj << 1;
  460. if( i & 0x80 ) {
  461. jj2 = 255 - jj2;
  462. }
  463. return jj2;
  464. }
  465. #elif EASE8_AVRASM == 1
  466. // This AVR asm version of ease8InOutQuad preserves one more
  467. // low-bit of precision than the C version, and is also slightly
  468. // smaller and faster.
  469. LIB8STATIC uint8_t ease8InOutQuad(uint8_t val) {
  470. uint8_t j=val;
  471. asm volatile (
  472. "sbrc %[val], 7 \n"
  473. "com %[j] \n"
  474. "mul %[j], %[j] \n"
  475. "add r0, %[j] \n"
  476. "ldi %[j], 0 \n"
  477. "adc %[j], r1 \n"
  478. "lsl r0 \n" // carry = high bit of low byte of mul product
  479. "rol %[j] \n" // j = (j * 2) + carry // preserve add'l bit of precision
  480. "sbrc %[val], 7 \n"
  481. "com %[j] \n"
  482. "clr __zero_reg__ \n"
  483. : [j] "+&a" (j)
  484. : [val] "a" (val)
  485. : "r0", "r1"
  486. );
  487. return j;
  488. }
  489. #else
  490. #error "No implementation for ease8InOutQuad available."
  491. #endif
  492. /// ease16InOutQuad: 16-bit quadratic ease-in / ease-out function
  493. // C implementation at this point
  494. LIB8STATIC uint16_t ease16InOutQuad( uint16_t i)
  495. {
  496. uint16_t j = i;
  497. if( j & 0x8000 ) {
  498. j = 65535 - j;
  499. }
  500. uint16_t jj = scale16( j, j);
  501. uint16_t jj2 = jj << 1;
  502. if( i & 0x8000 ) {
  503. jj2 = 65535 - jj2;
  504. }
  505. return jj2;
  506. }
  507. /// ease8InOutCubic: 8-bit cubic ease-in / ease-out function
  508. /// Takes around 18 cycles on AVR
  509. LIB8STATIC fract8 ease8InOutCubic( fract8 i)
  510. {
  511. uint8_t ii = scale8_LEAVING_R1_DIRTY( i, i);
  512. uint8_t iii = scale8_LEAVING_R1_DIRTY( ii, i);
  513. uint16_t r1 = (3 * (uint16_t)(ii)) - ( 2 * (uint16_t)(iii));
  514. /* the code generated for the above *'s automatically
  515. cleans up R1, so there's no need to explicitily call
  516. cleanup_R1(); */
  517. uint8_t result = r1;
  518. // if we got "256", return 255:
  519. if( r1 & 0x100 ) {
  520. result = 255;
  521. }
  522. return result;
  523. }
  524. /// ease8InOutApprox: fast, rough 8-bit ease-in/ease-out function
  525. /// shaped approximately like 'ease8InOutCubic',
  526. /// it's never off by more than a couple of percent
  527. /// from the actual cubic S-curve, and it executes
  528. /// more than twice as fast. Use when the cycles
  529. /// are more important than visual smoothness.
  530. /// Asm version takes around 7 cycles on AVR.
  531. #if EASE8_C == 1
  532. LIB8STATIC fract8 ease8InOutApprox( fract8 i)
  533. {
  534. if( i < 64) {
  535. // start with slope 0.5
  536. i /= 2;
  537. } else if( i > (255 - 64)) {
  538. // end with slope 0.5
  539. i = 255 - i;
  540. i /= 2;
  541. i = 255 - i;
  542. } else {
  543. // in the middle, use slope 192/128 = 1.5
  544. i -= 64;
  545. i += (i / 2);
  546. i += 32;
  547. }
  548. return i;
  549. }
  550. #elif EASE8_AVRASM == 1
  551. LIB8STATIC uint8_t ease8InOutApprox( fract8 i)
  552. {
  553. // takes around 7 cycles on AVR
  554. asm volatile (
  555. " subi %[i], 64 \n\t"
  556. " cpi %[i], 128 \n\t"
  557. " brcc Lshift_%= \n\t"
  558. // middle case
  559. " mov __tmp_reg__, %[i] \n\t"
  560. " lsr __tmp_reg__ \n\t"
  561. " add %[i], __tmp_reg__ \n\t"
  562. " subi %[i], 224 \n\t"
  563. " rjmp Ldone_%= \n\t"
  564. // start or end case
  565. "Lshift_%=: \n\t"
  566. " lsr %[i] \n\t"
  567. " subi %[i], 96 \n\t"
  568. "Ldone_%=: \n\t"
  569. : [i] "+&a" (i)
  570. :
  571. : "r0", "r1"
  572. );
  573. return i;
  574. }
  575. #else
  576. #error "No implementation for ease8 available."
  577. #endif
  578. /// triwave8: triangle (sawtooth) wave generator. Useful for
  579. /// turning a one-byte ever-increasing value into a
  580. /// one-byte value that oscillates up and down.
  581. ///
  582. /// input output
  583. /// 0..127 0..254 (positive slope)
  584. /// 128..255 254..0 (negative slope)
  585. ///
  586. /// On AVR this function takes just three cycles.
  587. ///
  588. LIB8STATIC uint8_t triwave8(uint8_t in)
  589. {
  590. if( in & 0x80) {
  591. in = 255 - in;
  592. }
  593. uint8_t out = in << 1;
  594. return out;
  595. }
  596. // quadwave8 and cubicwave8: S-shaped wave generators (like 'sine').
  597. // Useful for turning a one-byte 'counter' value into a
  598. // one-byte oscillating value that moves smoothly up and down,
  599. // with an 'acceleration' and 'deceleration' curve.
  600. //
  601. // These are even faster than 'sin8', and have
  602. // slightly different curve shapes.
  603. //
  604. /// quadwave8: quadratic waveform generator. Spends just a little more
  605. /// time at the limits than 'sine' does.
  606. LIB8STATIC uint8_t quadwave8(uint8_t in)
  607. {
  608. return ease8InOutQuad( triwave8( in));
  609. }
  610. /// cubicwave8: cubic waveform generator. Spends visibly more time
  611. /// at the limits than 'sine' does.
  612. LIB8STATIC uint8_t cubicwave8(uint8_t in)
  613. {
  614. return ease8InOutCubic( triwave8( in));
  615. }
  616. /// squarewave8: square wave generator. Useful for
  617. /// turning a one-byte ever-increasing value
  618. /// into a one-byte value that is either 0 or 255.
  619. /// The width of the output 'pulse' is
  620. /// determined by the pulsewidth argument:
  621. ///
  622. ///~~~
  623. /// If pulsewidth is 255, output is always 255.
  624. /// If pulsewidth < 255, then
  625. /// if input < pulsewidth then output is 255
  626. /// if input >= pulsewidth then output is 0
  627. ///~~~
  628. ///
  629. /// the output looking like:
  630. ///
  631. ///~~~
  632. /// 255 +--pulsewidth--+
  633. /// . | |
  634. /// 0 0 +--------(256-pulsewidth)--------
  635. ///~~~
  636. ///
  637. /// @param in
  638. /// @param pulsewidth
  639. /// @returns square wave output
  640. LIB8STATIC uint8_t squarewave8( uint8_t in, uint8_t pulsewidth)
  641. {
  642. if( in < pulsewidth || (pulsewidth == 255)) {
  643. return 255;
  644. } else {
  645. return 0;
  646. }
  647. }
  648. // Beat generators - These functions produce waves at a given
  649. // number of 'beats per minute'. Internally, they use
  650. // the Arduino function 'millis' to track elapsed time.
  651. // Accuracy is a bit better than one part in a thousand.
  652. //
  653. // beat8( BPM ) returns an 8-bit value that cycles 'BPM' times
  654. // per minute, rising from 0 to 255, resetting to zero,
  655. // rising up again, etc.. The output of this function
  656. // is suitable for feeding directly into sin8, and cos8,
  657. // triwave8, quadwave8, and cubicwave8.
  658. // beat16( BPM ) returns a 16-bit value that cycles 'BPM' times
  659. // per minute, rising from 0 to 65535, resetting to zero,
  660. // rising up again, etc. The output of this function is
  661. // suitable for feeding directly into sin16 and cos16.
  662. // beat88( BPM88) is the same as beat16, except that the BPM88 argument
  663. // MUST be in Q8.8 fixed point format, e.g. 120BPM must
  664. // be specified as 120*256 = 30720.
  665. // beatsin8( BPM, uint8_t low, uint8_t high) returns an 8-bit value that
  666. // rises and falls in a sine wave, 'BPM' times per minute,
  667. // between the values of 'low' and 'high'.
  668. // beatsin16( BPM, uint16_t low, uint16_t high) returns a 16-bit value
  669. // that rises and falls in a sine wave, 'BPM' times per
  670. // minute, between the values of 'low' and 'high'.
  671. // beatsin88( BPM88, ...) is the same as beatsin16, except that the
  672. // BPM88 argument MUST be in Q8.8 fixed point format,
  673. // e.g. 120BPM must be specified as 120*256 = 30720.
  674. //
  675. // BPM can be supplied two ways. The simpler way of specifying BPM is as
  676. // a simple 8-bit integer from 1-255, (e.g., "120").
  677. // The more sophisticated way of specifying BPM allows for fractional
  678. // "Q8.8" fixed point number (an 'accum88') with an 8-bit integer part and
  679. // an 8-bit fractional part. The easiest way to construct this is to multiply
  680. // a floating point BPM value (e.g. 120.3) by 256, (e.g. resulting in 30796
  681. // in this case), and pass that as the 16-bit BPM argument.
  682. // "BPM88" MUST always be specified in Q8.8 format.
  683. //
  684. // Originally designed to make an entire animation project pulse with brightness.
  685. // For that effect, add this line just above your existing call to "FastLED.show()":
  686. //
  687. // uint8_t bright = beatsin8( 60 /*BPM*/, 192 /*dimmest*/, 255 /*brightest*/ ));
  688. // FastLED.setBrightness( bright );
  689. // FastLED.show();
  690. //
  691. // The entire animation will now pulse between brightness 192 and 255 once per second.
  692. // The beat generators need access to a millisecond counter.
  693. // On Arduino, this is "millis()". On other platforms, you'll
  694. // need to provide a function with this signature:
  695. // uint32_t get_millisecond_timer();
  696. // that provides similar functionality.
  697. // You can also force use of the get_millisecond_timer function
  698. // by #defining USE_GET_MILLISECOND_TIMER.
  699. #if (defined(ARDUINO) || defined(SPARK) || defined(FASTLED_HAS_MILLIS)) && !defined(USE_GET_MILLISECOND_TIMER)
  700. // Forward declaration of Arduino function 'millis'.
  701. //uint32_t millis();
  702. #define GET_MILLIS millis
  703. #else
  704. uint32_t get_millisecond_timer(void);
  705. #define GET_MILLIS get_millisecond_timer
  706. #endif
  707. // beat16 generates a 16-bit 'sawtooth' wave at a given BPM,
  708. /// with BPM specified in Q8.8 fixed-point format; e.g.
  709. /// for this function, 120 BPM MUST BE specified as
  710. /// 120*256 = 30720.
  711. /// If you just want to specify "120", use beat16 or beat8.
  712. LIB8STATIC uint16_t beat88( accum88 beats_per_minute_88, uint32_t timebase)
  713. {
  714. // BPM is 'beats per minute', or 'beats per 60000ms'.
  715. // To avoid using the (slower) division operator, we
  716. // want to convert 'beats per 60000ms' to 'beats per 65536ms',
  717. // and then use a simple, fast bit-shift to divide by 65536.
  718. //
  719. // The ratio 65536:60000 is 279.620266667:256; we'll call it 280:256.
  720. // The conversion is accurate to about 0.05%, more or less,
  721. // e.g. if you ask for "120 BPM", you'll get about "119.93".
  722. return (((GET_MILLIS()) - timebase) * beats_per_minute_88 * 280) >> 16;
  723. }
  724. /// beat16 generates a 16-bit 'sawtooth' wave at a given BPM
  725. LIB8STATIC uint16_t beat16( accum88 beats_per_minute, uint32_t timebase)
  726. {
  727. // Convert simple 8-bit BPM's to full Q8.8 accum88's if needed
  728. if( beats_per_minute < 256) beats_per_minute <<= 8;
  729. return beat88(beats_per_minute, timebase);
  730. }
  731. /// beat8 generates an 8-bit 'sawtooth' wave at a given BPM
  732. LIB8STATIC uint8_t beat8( accum88 beats_per_minute, uint32_t timebase)
  733. {
  734. return beat16( beats_per_minute, timebase) >> 8;
  735. }
  736. /// beatsin88 generates a 16-bit sine wave at a given BPM,
  737. /// that oscillates within a given range.
  738. /// For this function, BPM MUST BE SPECIFIED as
  739. /// a Q8.8 fixed-point value; e.g. 120BPM must be
  740. /// specified as 120*256 = 30720.
  741. /// If you just want to specify "120", use beatsin16 or beatsin8.
  742. LIB8STATIC uint16_t beatsin88( accum88 beats_per_minute_88, uint16_t lowest, uint16_t highest, uint32_t timebase, uint16_t phase_offset)
  743. {
  744. uint16_t beat = beat88( beats_per_minute_88, timebase);
  745. uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
  746. uint16_t rangewidth = highest - lowest;
  747. uint16_t scaledbeat = scale16( beatsin, rangewidth);
  748. uint16_t result = lowest + scaledbeat;
  749. return result;
  750. }
  751. /// beatsin16 generates a 16-bit sine wave at a given BPM,
  752. /// that oscillates within a given range.
  753. LIB8STATIC uint16_t beatsin16(accum88 beats_per_minute, uint16_t lowest, uint16_t highest, uint32_t timebase, uint16_t phase_offset)
  754. {
  755. uint16_t beat = beat16( beats_per_minute, timebase);
  756. uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
  757. uint16_t rangewidth = highest - lowest;
  758. uint16_t scaledbeat = scale16( beatsin, rangewidth);
  759. uint16_t result = lowest + scaledbeat;
  760. return result;
  761. }
  762. /// beatsin8 generates an 8-bit sine wave at a given BPM,
  763. /// that oscillates within a given range.
  764. LIB8STATIC uint8_t beatsin8( accum88 beats_per_minute, uint8_t lowest, uint8_t highest, uint32_t timebase, uint8_t phase_offset)
  765. {
  766. uint8_t beat = beat8( beats_per_minute, timebase);
  767. uint8_t beatsin = sin8( beat + phase_offset);
  768. uint8_t rangewidth = highest - lowest;
  769. uint8_t scaledbeat = scale8( beatsin, rangewidth);
  770. uint8_t result = lowest + scaledbeat;
  771. return result;
  772. }
  773. /// Return the current seconds since boot in a 16-bit value. Used as part of the
  774. /// "every N time-periods" mechanism
  775. LIB8STATIC uint16_t seconds16(void)
  776. {
  777. uint32_t ms = GET_MILLIS();
  778. uint16_t s16;
  779. s16 = ms / 1000;
  780. return s16;
  781. }
  782. /// Return the current minutes since boot in a 16-bit value. Used as part of the
  783. /// "every N time-periods" mechanism
  784. LIB8STATIC uint16_t minutes16(void)
  785. {
  786. uint32_t ms = GET_MILLIS();
  787. uint16_t m16;
  788. m16 = (ms / (60000L)) & 0xFFFF;
  789. return m16;
  790. }
  791. /// Return the current hours since boot in an 8-bit value. Used as part of the
  792. /// "every N time-periods" mechanism
  793. LIB8STATIC uint8_t hours8(void)
  794. {
  795. uint32_t ms = GET_MILLIS();
  796. uint8_t h8;
  797. h8 = (ms / (3600000L)) & 0xFF;
  798. return h8;
  799. }
  800. ///@}
  801. #endif