PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1174 行
37KB

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