25880浏览
楼主: 驴友花雕

[项目] 【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带

[复制链接]

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 10:49:18

实验场景图  动态图

【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带图1
回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 12:59:27

  【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  实验程序十四:闪烁的“假日”灯,淡入淡出

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序十四:闪烁的“假日”灯,淡入淡出
  5. */
  6. #include "FastLED.h"
  7. #define NUM_LEDS     24
  8. #define LED_TYPE   WS2811
  9. #define COLOR_ORDER   GRB
  10. #define DATA_PIN        6
  11. //#define CLK_PIN       4
  12. #define VOLTS          12
  13. #define MAX_MA       4000
  14. CRGBArray<NUM_LEDS> leds;
  15. #define TWINKLE_SPEED 7 //整体闪烁速度,0(非常慢)到 8(非常快)
  16. #define TWINKLE_DENSITY 5 // 整体闪烁密度,0(NONE 点亮)到 8(ALL 一次点亮)
  17. #define SECONDS_PER_PALETTE  10 // 多久更换一次调色板
  18. // Background color for 'unlit' pixels
  19. // Can be set to CRGB::Black if desired.
  20. CRGB gBackgroundColor = CRGB::Black;
  21. // Example of dim incandescent fairy light background color
  22. // CRGB gBackgroundColor = CRGB(CRGB::FairyLight).nscale8_video(16);
  23. // If AUTO_SELECT_BACKGROUND_COLOR is set to 1,
  24. // then for any palette where the first two entries
  25. // are the same, a dimmed version of that color will
  26. // automatically be used as the background color.
  27. #define AUTO_SELECT_BACKGROUND_COLOR 0
  28. // If COOL_LIKE_INCANDESCENT is set to 1, colors will
  29. // fade out slighted 'reddened', similar to how
  30. // incandescent bulbs change color as they get dim down.
  31. #define COOL_LIKE_INCANDESCENT 1
  32. CRGBPalette16 gCurrentPalette;
  33. CRGBPalette16 gTargetPalette;
  34. void setup() {
  35.   delay( 1000 ); //safety startup delay
  36.   FastLED.setMaxPowerInVoltsAndMilliamps( VOLTS, MAX_MA);
  37.   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
  38.     .setCorrection(TypicalLEDStrip);
  39.   chooseNextColorPalette(gTargetPalette);
  40. }
  41. void loop(){
  42.   EVERY_N_SECONDS( SECONDS_PER_PALETTE ) {
  43.     chooseNextColorPalette( gTargetPalette );
  44.   }
  45.   
  46.   EVERY_N_MILLISECONDS( 10 ) {
  47.     nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 12);
  48.   }
  49.   drawTwinkles( leds);
  50.   
  51.   FastLED.show();
  52. }
  53. //  This function loops over each pixel, calculates the
  54. //  adjusted 'clock' that this pixel should use, and calls
  55. //  "CalculateOneTwinkle" on each pixel.  It then displays
  56. //  either the twinkle color of the background color,
  57. //  whichever is brighter.
  58. void drawTwinkles( CRGBSet& L){
  59.   // "PRNG16" is the pseudorandom number generator
  60.   // It MUST be reset to the same starting value each time
  61.   // this function is called, so that the sequence of 'random'
  62.   // numbers that it generates is (paradoxically) stable.
  63.   uint16_t PRNG16 = 11337;
  64.   
  65.   uint32_t clock32 = millis();
  66.   // Set up the background color, "bg".
  67.   // if AUTO_SELECT_BACKGROUND_COLOR == 1, and the first two colors of
  68.   // the current palette are identical, then a deeply faded version of
  69.   // that color is used for the background color
  70.   CRGB bg;
  71.   if( (AUTO_SELECT_BACKGROUND_COLOR == 1) &&
  72.       (gCurrentPalette[0] == gCurrentPalette[1] )) {
  73.     bg = gCurrentPalette[0];
  74.     uint8_t bglight = bg.getAverageLight();
  75.     if( bglight > 64) {
  76.       bg.nscale8_video( 16); // very bright, so scale to 1/16th
  77.     } else if( bglight > 16) {
  78.       bg.nscale8_video( 64); // not that bright, so scale to 1/4th
  79.     } else {
  80.       bg.nscale8_video( 86); // dim, scale to 1/3rd.
  81.     }
  82.   } else {
  83.     bg = gBackgroundColor; // just use the explicitly defined background color
  84.   }
  85.   uint8_t backgroundBrightness = bg.getAverageLight();
  86.   
  87.   for( CRGB& pixel: L) {
  88.     PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
  89.     uint16_t myclockoffset16= PRNG16; // use that number as clock offset
  90.     PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
  91.     // use that number as clock speed adjustment factor (in 8ths, from 8/8ths to 23/8ths)
  92.     uint8_t myspeedmultiplierQ5_3 =  ((((PRNG16 & 0xFF)>>4) + (PRNG16 & 0x0F)) & 0x0F) + 0x08;
  93.     uint32_t myclock30 = (uint32_t)((clock32 * myspeedmultiplierQ5_3) >> 3) + myclockoffset16;
  94.     uint8_t  myunique8 = PRNG16 >> 8; // get 'salt' value for this pixel
  95.     // We now have the adjusted 'clock' for this pixel, now we call
  96.     // the function that computes what color the pixel should be based
  97.     // on the "brightness = f( time )" idea.
  98.     CRGB c = computeOneTwinkle( myclock30, myunique8);
  99.     uint8_t cbright = c.getAverageLight();
  100.     int16_t deltabright = cbright - backgroundBrightness;
  101.     if( deltabright >= 32 || (!bg)) {
  102.       // If the new pixel is significantly brighter than the background color,
  103.       // use the new color.
  104.       pixel = c;
  105.     } else if( deltabright > 0 ) {
  106.       // If the new pixel is just slightly brighter than the background color,
  107.       // mix a blend of the new color and the background color
  108.       pixel = blend( bg, c, deltabright * 8);
  109.     } else {
  110.       // if the new pixel is not at all brighter than the background color,
  111.       // just use the background color.
  112.       pixel = bg;
  113.     }
  114.   }
  115. }
  116. //  This function takes a time in pseudo-milliseconds,
  117. //  figures out brightness = f( time ), and also hue = f( time )
  118. //  The 'low digits' of the millisecond time are used as
  119. //  input to the brightness wave function.  
  120. //  The 'high digits' are used to select a color, so that the color
  121. //  does not change over the course of the fade-in, fade-out
  122. //  of one cycle of the brightness wave function.
  123. //  The 'high digits' are also used to determine whether this pixel
  124. //  should light at all during this cycle, based on the TWINKLE_DENSITY.
  125. CRGB computeOneTwinkle( uint32_t ms, uint8_t salt)
  126. {
  127.   uint16_t ticks = ms >> (8-TWINKLE_SPEED);
  128.   uint8_t fastcycle8 = ticks;
  129.   uint16_t slowcycle16 = (ticks >> 8) + salt;
  130.   slowcycle16 += sin8( slowcycle16);
  131.   slowcycle16 =  (slowcycle16 * 2053) + 1384;
  132.   uint8_t slowcycle8 = (slowcycle16 & 0xFF) + (slowcycle16 >> 8);
  133.   
  134.   uint8_t bright = 0;
  135.   if( ((slowcycle8 & 0x0E)/2) < TWINKLE_DENSITY) {
  136.     bright = attackDecayWave8( fastcycle8);
  137.   }
  138.   uint8_t hue = slowcycle8 - salt;
  139.   CRGB c;
  140.   if( bright > 0) {
  141.     c = ColorFromPalette( gCurrentPalette, hue, bright, NOBLEND);
  142.     if( COOL_LIKE_INCANDESCENT == 1 ) {
  143.       coolLikeIncandescent( c, fastcycle8);
  144.     }
  145.   } else {
  146.     c = CRGB::Black;
  147.   }
  148.   return c;
  149. }
  150. // This function is like 'triwave8', which produces a
  151. // symmetrical up-and-down triangle sawtooth waveform, except that this
  152. // function produces a triangle wave with a faster attack and a slower decay:
  153. //
  154. //     / \
  155. //    /     \
  156. //   /         \
  157. //  /             \
  158. //
  159. uint8_t attackDecayWave8( uint8_t i)
  160. {
  161.   if( i < 86) {
  162.     return i * 3;
  163.   } else {
  164.     i -= 86;
  165.     return 255 - (i + (i/2));
  166.   }
  167. }
  168. // This function takes a pixel, and if its in the 'fading down'
  169. // part of the cycle, it adjusts the color a little bit like the
  170. // way that incandescent bulbs fade toward 'red' as they dim.
  171. void coolLikeIncandescent( CRGB& c, uint8_t phase)
  172. {
  173.   if( phase < 128) return;
  174.   uint8_t cooling = (phase - 128) >> 4;
  175.   c.g = qsub8( c.g, cooling);
  176.   c.b = qsub8( c.b, cooling * 2);
  177. }
  178. // A mostly red palette with green accents and white trim.
  179. // "CRGB::Gray" is used as white to keep the brightness more uniform.
  180. const TProgmemRGBPalette16 RedGreenWhite_p FL_PROGMEM =
  181. {  CRGB::Red, CRGB::Red, CRGB::Red, CRGB::Red,
  182.    CRGB::Red, CRGB::Red, CRGB::Red, CRGB::Red,
  183.    CRGB::Red, CRGB::Red, CRGB::Gray, CRGB::Gray,
  184.    CRGB::Green, CRGB::Green, CRGB::Green, CRGB::Green };
  185. // A mostly (dark) green palette with red berries.
  186. #define Holly_Green 0x00580c
  187. #define Holly_Red   0xB00402
  188. const TProgmemRGBPalette16 Holly_p FL_PROGMEM =
  189. {  Holly_Green, Holly_Green, Holly_Green, Holly_Green,
  190.    Holly_Green, Holly_Green, Holly_Green, Holly_Green,
  191.    Holly_Green, Holly_Green, Holly_Green, Holly_Green,
  192.    Holly_Green, Holly_Green, Holly_Green, Holly_Red
  193. };
  194. // A red and white striped palette
  195. // "CRGB::Gray" is used as white to keep the brightness more uniform.
  196. const TProgmemRGBPalette16 RedWhite_p FL_PROGMEM =
  197. {  CRGB::Red,  CRGB::Red,  CRGB::Red,  CRGB::Red,
  198.    CRGB::Gray, CRGB::Gray, CRGB::Gray, CRGB::Gray,
  199.    CRGB::Red,  CRGB::Red,  CRGB::Red,  CRGB::Red,
  200.    CRGB::Gray, CRGB::Gray, CRGB::Gray, CRGB::Gray };
  201. // A mostly blue palette with white accents.
  202. // "CRGB::Gray" is used as white to keep the brightness more uniform.
  203. const TProgmemRGBPalette16 BlueWhite_p FL_PROGMEM =
  204. {  CRGB::Blue, CRGB::Blue, CRGB::Blue, CRGB::Blue,
  205.    CRGB::Blue, CRGB::Blue, CRGB::Blue, CRGB::Blue,
  206.    CRGB::Blue, CRGB::Blue, CRGB::Blue, CRGB::Blue,
  207.    CRGB::Blue, CRGB::Gray, CRGB::Gray, CRGB::Gray };
  208. // A pure "fairy light" palette with some brightness variations
  209. #define HALFFAIRY ((CRGB::FairyLight & 0xFEFEFE) / 2)
  210. #define QUARTERFAIRY ((CRGB::FairyLight & 0xFCFCFC) / 4)
  211. const TProgmemRGBPalette16 FairyLight_p FL_PROGMEM =
  212. {  CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight,
  213.    HALFFAIRY,        HALFFAIRY,        CRGB::FairyLight, CRGB::FairyLight,
  214.    QUARTERFAIRY,     QUARTERFAIRY,     CRGB::FairyLight, CRGB::FairyLight,
  215.    CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight };
  216. // A palette of soft snowflakes with the occasional bright one
  217. const TProgmemRGBPalette16 Snow_p FL_PROGMEM =
  218. {  0x304048, 0x304048, 0x304048, 0x304048,
  219.    0x304048, 0x304048, 0x304048, 0x304048,
  220.    0x304048, 0x304048, 0x304048, 0x304048,
  221.    0x304048, 0x304048, 0x304048, 0xE0F0FF };
  222. // A palette reminiscent of large 'old-school' C9-size tree lights
  223. // in the five classic colors: red, orange, green, blue, and white.
  224. #define C9_Red    0xB80400
  225. #define C9_Orange 0x902C02
  226. #define C9_Green  0x046002
  227. #define C9_Blue   0x070758
  228. #define C9_White  0x606820
  229. const TProgmemRGBPalette16 RetroC9_p FL_PROGMEM =
  230. {  C9_Red,    C9_Orange, C9_Red,    C9_Orange,
  231.    C9_Orange, C9_Red,    C9_Orange, C9_Red,
  232.    C9_Green,  C9_Green,  C9_Green,  C9_Green,
  233.    C9_Blue,   C9_Blue,   C9_Blue,
  234.    C9_White
  235. };
  236. // A cold, icy pale blue palette
  237. #define Ice_Blue1 0x0C1040
  238. #define Ice_Blue2 0x182080
  239. #define Ice_Blue3 0x5080C0
  240. const TProgmemRGBPalette16 Ice_p FL_PROGMEM =
  241. {
  242.   Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
  243.   Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
  244.   Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
  245.   Ice_Blue2, Ice_Blue2, Ice_Blue2, Ice_Blue3
  246. };
  247. // Add or remove palette names from this list to control which color
  248. // palettes are used, and in what order.
  249. const TProgmemRGBPalette16* ActivePaletteList[] = {
  250.   &RetroC9_p,
  251.   &BlueWhite_p,
  252.   &RainbowColors_p,
  253.   &FairyLight_p,
  254.   &RedGreenWhite_p,
  255.   &PartyColors_p,
  256.   &RedWhite_p,
  257.   &Snow_p,
  258.   &Holly_p,
  259.   &Ice_p  
  260. };
  261. // Advance to the next color palette in the list (above).
  262. void chooseNextColorPalette( CRGBPalette16& pal)
  263. {
  264.   const uint8_t numberOfPalettes = sizeof(ActivePaletteList) / sizeof(ActivePaletteList[0]);
  265.   static uint8_t whichPalette = -1;
  266.   whichPalette = addmod8( whichPalette, 1, numberOfPalettes);
  267.   pal = *(ActivePaletteList[whichPalette]);
  268. }
复制代码


回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 13:16:40

实验场景图  动态图

【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带图1
回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 15:34:03

  【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  实验程序十五:动画,不断变化的彩虹

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序十五:动画,不断变化的彩虹
  5. */
  6. #include "FastLED.h"
  7. #if FASTLED_VERSION < 3001000
  8. #error "Requires FastLED 3.1 or later; check github for latest code."
  9. #endif
  10. #define DATA_PIN    6
  11. //#define CLK_PIN   4
  12. #define LED_TYPE    WS2811
  13. #define COLOR_ORDER GRB
  14. #define NUM_LEDS    24
  15. #define BRIGHTNESS  33
  16. CRGB leds[NUM_LEDS];
  17. void setup() {
  18.   delay(3000); // 3 second delay for recovery
  19.   
  20.   // tell FastLED about the LED strip configuration
  21.   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
  22.     .setCorrection(TypicalLEDStrip)
  23.     .setDither(BRIGHTNESS < 255);
  24.   // set master brightness control
  25.   FastLED.setBrightness(BRIGHTNESS);
  26. }
  27. void loop(){
  28.   pride();
  29.   FastLED.show();  
  30. }
  31. // This function draws rainbows with an ever-changing,
  32. // widely-varying set of parameters.
  33. void pride()
  34. {
  35.   static uint16_t sPseudotime = 0;
  36.   static uint16_t sLastMillis = 0;
  37.   static uint16_t sHue16 = 0;
  38.   uint8_t sat8 = beatsin88( 87, 220, 250);
  39.   uint8_t brightdepth = beatsin88( 341, 96, 224);
  40.   uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
  41.   uint8_t msmultiplier = beatsin88(147, 23, 60);
  42.   uint16_t hue16 = sHue16;//gHue * 256;
  43.   uint16_t hueinc16 = beatsin88(113, 1, 3000);
  44.   
  45.   uint16_t ms = millis();
  46.   uint16_t deltams = ms - sLastMillis ;
  47.   sLastMillis  = ms;
  48.   sPseudotime += deltams * msmultiplier;
  49.   sHue16 += deltams * beatsin88( 400, 5,9);
  50.   uint16_t brightnesstheta16 = sPseudotime;
  51.   
  52.   for( uint16_t i = 0 ; i < NUM_LEDS; i++) {
  53.     hue16 += hueinc16;
  54.     uint8_t hue8 = hue16 / 256;
  55.     brightnesstheta16  += brightnessthetainc16;
  56.     uint16_t b16 = sin16( brightnesstheta16  ) + 32768;
  57.     uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
  58.     uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
  59.     bri8 += (255 - brightdepth);
  60.    
  61.     CRGB newcolor = CHSV( hue8, sat8, bri8);
  62.    
  63.     uint16_t pixelnumber = i;
  64.     pixelnumber = (NUM_LEDS-1) - pixelnumber;
  65.    
  66.     nblend( leds[pixelnumber], newcolor, 64);
  67.   }
  68. }
复制代码


回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 15:53:33

实验场景图

【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带图1
回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 16:04:38

  【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  实验程序十六:太平洋——‎‎温柔的蓝绿色海浪

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序十六:太平洋——‎‎温柔的蓝绿色海浪
  5. */
  6. #define FASTLED_ALLOW_INTERRUPTS 0
  7. #include <FastLED.h>
  8. FASTLED_USING_NAMESPACE
  9. #define DATA_PIN            6
  10. #define NUM_LEDS            24
  11. #define MAX_POWER_MILLIAMPS 500
  12. #define LED_TYPE            WS2812B
  13. #define COLOR_ORDER         GRB
  14. //////////////////////////////////////////////////////////////////////////
  15. CRGB leds[NUM_LEDS];
  16. void setup() {
  17.   delay( 3000); // 3 second delay for boot recovery, and a moment of silence
  18.   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
  19.         .setCorrection( TypicalLEDStrip );
  20.   FastLED.setMaxPowerInVoltsAndMilliamps( 5, MAX_POWER_MILLIAMPS);
  21. }
  22. void loop(){
  23.   EVERY_N_MILLISECONDS( 20) {
  24.     pacifica_loop();
  25.     FastLED.show();
  26.   }
  27. }
  28. //////////////////////////////////////////////////////////////////////////
  29. //
  30. // The code for this animation is more complicated than other examples, and
  31. // while it is "ready to run", and documented in general, it is probably not
  32. // the best starting point for learning.  Nevertheless, it does illustrate some
  33. // useful techniques.
  34. //
  35. //////////////////////////////////////////////////////////////////////////
  36. //
  37. // In this animation, there are four "layers" of waves of light.  
  38. //
  39. // Each layer moves independently, and each is scaled separately.
  40. //
  41. // All four wave layers are added together on top of each other, and then
  42. // another filter is applied that adds "whitecaps" of brightness where the
  43. // waves line up with each other more.  Finally, another pass is taken
  44. // over the led array to 'deepen' (dim) the blues and greens.
  45. //
  46. // The speed and scale and motion each layer varies slowly within independent
  47. // hand-chosen ranges, which is why the code has a lot of low-speed 'beatsin8' functions
  48. // with a lot of oddly specific numeric ranges.
  49. //
  50. // These three custom blue-green color palettes were inspired by the colors found in
  51. // the waters off the southern coast of California, https://goo.gl/maps/QQgd97jjHesHZVxQ7
  52. //
  53. CRGBPalette16 pacifica_palette_1 =
  54.     { 0x000507, 0x000409, 0x00030B, 0x00030D, 0x000210, 0x000212, 0x000114, 0x000117,
  55.       0x000019, 0x00001C, 0x000026, 0x000031, 0x00003B, 0x000046, 0x14554B, 0x28AA50 };
  56. CRGBPalette16 pacifica_palette_2 =
  57.     { 0x000507, 0x000409, 0x00030B, 0x00030D, 0x000210, 0x000212, 0x000114, 0x000117,
  58.       0x000019, 0x00001C, 0x000026, 0x000031, 0x00003B, 0x000046, 0x0C5F52, 0x19BE5F };
  59. CRGBPalette16 pacifica_palette_3 =
  60.     { 0x000208, 0x00030E, 0x000514, 0x00061A, 0x000820, 0x000927, 0x000B2D, 0x000C33,
  61.       0x000E39, 0x001040, 0x001450, 0x001860, 0x001C70, 0x002080, 0x1040BF, 0x2060FF };
  62. void pacifica_loop()
  63. {
  64.   // Increment the four "color index start" counters, one for each wave layer.
  65.   // Each is incremented at a different speed, and the speeds vary over time.
  66.   static uint16_t sCIStart1, sCIStart2, sCIStart3, sCIStart4;
  67.   static uint32_t sLastms = 0;
  68.   uint32_t ms = GET_MILLIS();
  69.   uint32_t deltams = ms - sLastms;
  70.   sLastms = ms;
  71.   uint16_t speedfactor1 = beatsin16(3, 179, 269);
  72.   uint16_t speedfactor2 = beatsin16(4, 179, 269);
  73.   uint32_t deltams1 = (deltams * speedfactor1) / 256;
  74.   uint32_t deltams2 = (deltams * speedfactor2) / 256;
  75.   uint32_t deltams21 = (deltams1 + deltams2) / 2;
  76.   sCIStart1 += (deltams1 * beatsin88(1011,10,13));
  77.   sCIStart2 -= (deltams21 * beatsin88(777,8,11));
  78.   sCIStart3 -= (deltams1 * beatsin88(501,5,7));
  79.   sCIStart4 -= (deltams2 * beatsin88(257,4,6));
  80.   // Clear out the LED array to a dim background blue-green
  81.   fill_solid( leds, NUM_LEDS, CRGB( 2, 6, 10));
  82.   // Render each of four layers, with different scales and speeds, that vary over time
  83.   pacifica_one_layer( pacifica_palette_1, sCIStart1, beatsin16( 3, 11 * 256, 14 * 256), beatsin8( 10, 70, 130), 0-beat16( 301) );
  84.   pacifica_one_layer( pacifica_palette_2, sCIStart2, beatsin16( 4,  6 * 256,  9 * 256), beatsin8( 17, 40,  80), beat16( 401) );
  85.   pacifica_one_layer( pacifica_palette_3, sCIStart3, 6 * 256, beatsin8( 9, 10,38), 0-beat16(503));
  86.   pacifica_one_layer( pacifica_palette_3, sCIStart4, 5 * 256, beatsin8( 8, 10,28), beat16(601));
  87.   // Add brighter 'whitecaps' where the waves lines up more
  88.   pacifica_add_whitecaps();
  89.   // Deepen the blues and greens a bit
  90.   pacifica_deepen_colors();
  91. }
  92. // Add one layer of waves into the led array
  93. void pacifica_one_layer( CRGBPalette16& p, uint16_t cistart, uint16_t wavescale, uint8_t bri, uint16_t ioff)
  94. {
  95.   uint16_t ci = cistart;
  96.   uint16_t waveangle = ioff;
  97.   uint16_t wavescale_half = (wavescale / 2) + 20;
  98.   for( uint16_t i = 0; i < NUM_LEDS; i++) {
  99.     waveangle += 250;
  100.     uint16_t s16 = sin16( waveangle ) + 32768;
  101.     uint16_t cs = scale16( s16 , wavescale_half ) + wavescale_half;
  102.     ci += cs;
  103.     uint16_t sindex16 = sin16( ci) + 32768;
  104.     uint8_t sindex8 = scale16( sindex16, 240);
  105.     CRGB c = ColorFromPalette( p, sindex8, bri, LINEARBLEND);
  106.     leds[i] += c;
  107.   }
  108. }
  109. // Add extra 'white' to areas where the four layers of light have lined up brightly
  110. void pacifica_add_whitecaps()
  111. {
  112.   uint8_t basethreshold = beatsin8( 9, 55, 65);
  113.   uint8_t wave = beat8( 7 );
  114.   
  115.   for( uint16_t i = 0; i < NUM_LEDS; i++) {
  116.     uint8_t threshold = scale8( sin8( wave), 20) + basethreshold;
  117.     wave += 7;
  118.     uint8_t l = leds[i].getAverageLight();
  119.     if( l > threshold) {
  120.       uint8_t overage = l - threshold;
  121.       uint8_t overage2 = qadd8( overage, overage);
  122.       leds[i] += CRGB( overage, overage2, qadd8( overage2, overage2));
  123.     }
  124.   }
  125. }
  126. // Deepen the blues and greens
  127. void pacifica_deepen_colors()
  128. {
  129.   for( uint16_t i = 0; i < NUM_LEDS; i++) {
  130.     leds[i].blue = scale8( leds[i].blue,  145);
  131.     leds[i].green= scale8( leds[i].green, 200);
  132.     leds[i] |= CRGB( 2, 5, 7);
  133.   }
  134. }
复制代码


回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 16:37:12

  【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  实验程序十七:内置调色板(森林,云彩,熔岩,海洋,派对)

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序十七:内置调色板(森林,云彩,熔岩,海洋,派对)
  5. */
  6. #include <FastLED.h>
  7. #define LED_PIN     6
  8. #define BRIGHTNESS  24
  9. #define LED_TYPE    WS2811
  10. #define COLOR_ORDER GRB
  11. #define BRIGHTNESS  33
  12. // Params for width and height
  13. const uint8_t kMatrixWidth  = 24;
  14. const uint8_t kMatrixHeight = 1;
  15. // Param for different pixel layouts
  16. const bool    kMatrixSerpentineLayout = true;
  17. #define NUM_LEDS (kMatrixWidth * kMatrixHeight)
  18. #define MAX_DIMENSION ((kMatrixWidth>kMatrixHeight) ? kMatrixWidth : kMatrixHeight)
  19. // The leds
  20. CRGB leds[kMatrixWidth * kMatrixHeight];
  21. // The 16 bit version of our coordinates
  22. static uint16_t x;
  23. static uint16_t y;
  24. static uint16_t z;
  25. // We're using the x/y dimensions to map to the x/y pixels on the matrix.  We'll
  26. // use the z-axis for "time".  speed determines how fast time moves forward.  Try
  27. // 1 for a very slow moving effect, or 60 for something that ends up looking like
  28. // water.
  29. uint16_t speed = 20; // speed is set dynamically once we've started up
  30. // Scale determines how far apart the pixels in our noise matrix are.  Try
  31. // changing these values around to see how it affects the motion of the display.  The
  32. // higher the value of scale, the more "zoomed out" the noise iwll be.  A value
  33. // of 1 will be so zoomed in, you'll mostly see solid colors.
  34. uint16_t scale = 30; // scale is set dynamically once we've started up
  35. // This is the array that we keep our computed noise values in
  36. uint8_t noise[MAX_DIMENSION][MAX_DIMENSION];
  37. CRGBPalette16 currentPalette( PartyColors_p );
  38. uint8_t       colorLoop = 1;
  39. void setup() {
  40.   delay(3000);
  41.   FastLED.addLeds<LED_TYPE,LED_PIN,COLOR_ORDER>(leds,NUM_LEDS);
  42.   FastLED.setBrightness(BRIGHTNESS);
  43.   // Initialize our coordinates to some random values
  44.   x = random16();
  45.   y = random16();
  46.   z = random16();
  47. }
  48. // Fill the x/y array of 8-bit noise values using the inoise8 function.
  49. void fillnoise8() {
  50.   // If we're runing at a low "speed", some 8-bit artifacts become visible
  51.   // from frame-to-frame.  In order to reduce this, we can do some fast data-smoothing.
  52.   // The amount of data smoothing we're doing depends on "speed".
  53.   uint8_t dataSmoothing = 0;
  54.   if( speed < 50) {
  55.     dataSmoothing = 200 - (speed * 4);
  56.   }
  57.   
  58.   for(int i = 0; i < MAX_DIMENSION; i++) {
  59.     int ioffset = scale * i;
  60.     for(int j = 0; j < MAX_DIMENSION; j++) {
  61.       int joffset = scale * j;
  62.       
  63.       uint8_t data = inoise8(x + ioffset,y + joffset,z);
  64.       // The range of the inoise8 function is roughly 16-238.
  65.       // These two operations expand those values out to roughly 0..255
  66.       // You can comment them out if you want the raw noise data.
  67.       data = qsub8(data,16);
  68.       data = qadd8(data,scale8(data,39));
  69.       if( dataSmoothing ) {
  70.         uint8_t olddata = noise[i][j];
  71.         uint8_t newdata = scale8( olddata, dataSmoothing) + scale8( data, 256 - dataSmoothing);
  72.         data = newdata;
  73.       }
  74.       
  75.       noise[i][j] = data;
  76.     }
  77.   }
  78.   
  79.   z += speed;
  80.   
  81.   // apply slow drift to X and Y, just for visual variation.
  82.   x += speed / 8;
  83.   y -= speed / 16;
  84. }
  85. void mapNoiseToLEDsUsingPalette()
  86. {
  87.   static uint8_t ihue=0;
  88.   
  89.   for(int i = 0; i < kMatrixWidth; i++) {
  90.     for(int j = 0; j < kMatrixHeight; j++) {
  91.       // We use the value at the (i,j) coordinate in the noise
  92.       // array for our brightness, and the flipped value from (j,i)
  93.       // for our pixel's index into the color palette.
  94.       uint8_t index = noise[j][i];
  95.       uint8_t bri =   noise[i][j];
  96.       // if this palette is a 'loop', add a slowly-changing base value
  97.       if( colorLoop) {
  98.         index += ihue;
  99.       }
  100.       // brighten up, as the color palette itself often contains the
  101.       // light/dark dynamic range desired
  102.       if( bri > 127 ) {
  103.         bri = 255;
  104.       } else {
  105.         bri = dim8_raw( bri * 2);
  106.       }
  107.       CRGB color = ColorFromPalette( currentPalette, index, bri);
  108.       leds[XY(i,j)] = color;
  109.     }
  110.   }
  111.   
  112.   ihue+=1;
  113. }
  114. void loop() {
  115.   // Periodically choose a new palette, speed, and scale
  116.   ChangePaletteAndSettingsPeriodically();
  117.   // generate noise data
  118.   fillnoise8();
  119.   
  120.   // convert the noise data to colors in the LED array
  121.   // using the current palette
  122.   mapNoiseToLEDsUsingPalette();
  123.   FastLED.show();
  124.   // delay(10);
  125. }
  126. #define HOLD_PALETTES_X_TIMES_AS_LONG 1
  127. void ChangePaletteAndSettingsPeriodically()
  128. {
  129.   uint8_t secondHand = ((millis() / 1000) / HOLD_PALETTES_X_TIMES_AS_LONG) % 60;
  130.   static uint8_t lastSecond = 99;
  131.   
  132.   if( lastSecond != secondHand) {
  133.     lastSecond = secondHand;
  134.     if( secondHand ==  0)  { currentPalette = RainbowColors_p;         speed = 20; scale = 30; colorLoop = 1; }
  135.     if( secondHand ==  5)  { SetupPurpleAndGreenPalette();             speed = 10; scale = 50; colorLoop = 1; }
  136.     if( secondHand == 10)  { SetupBlackAndWhiteStripedPalette();       speed = 20; scale = 30; colorLoop = 1; }
  137.     if( secondHand == 15)  { currentPalette = ForestColors_p;          speed =  8; scale =120; colorLoop = 0; }
  138.     if( secondHand == 20)  { currentPalette = CloudColors_p;           speed =  4; scale = 30; colorLoop = 0; }
  139.     if( secondHand == 25)  { currentPalette = LavaColors_p;            speed =  8; scale = 50; colorLoop = 0; }
  140.     if( secondHand == 30)  { currentPalette = OceanColors_p;           speed = 20; scale = 90; colorLoop = 0; }
  141.     if( secondHand == 35)  { currentPalette = PartyColors_p;           speed = 20; scale = 30; colorLoop = 1; }
  142.     if( secondHand == 40)  { SetupRandomPalette();                     speed = 20; scale = 20; colorLoop = 1; }
  143.     if( secondHand == 45)  { SetupRandomPalette();                     speed = 50; scale = 50; colorLoop = 1; }
  144.     if( secondHand == 50)  { SetupRandomPalette();                     speed = 90; scale = 90; colorLoop = 1; }
  145.     if( secondHand == 55)  { currentPalette = RainbowStripeColors_p;   speed = 30; scale = 20; colorLoop = 1; }
  146.   }
  147. }
  148. // This function generates a random palette that's a gradient
  149. // between four different colors.  The first is a dim hue, the second is
  150. // a bright hue, the third is a bright pastel, and the last is
  151. // another bright hue.  This gives some visual bright/dark variation
  152. // which is more interesting than just a gradient of different hues.
  153. void SetupRandomPalette()
  154. {
  155.   currentPalette = CRGBPalette16(
  156.                       CHSV( random8(), 255, 32),
  157.                       CHSV( random8(), 255, 255),
  158.                       CHSV( random8(), 128, 255),
  159.                       CHSV( random8(), 255, 255));
  160. }
  161. // This function sets up a palette of black and white stripes,
  162. // using code.  Since the palette is effectively an array of
  163. // sixteen CRGB colors, the various fill_* functions can be used
  164. // to set them up.
  165. void SetupBlackAndWhiteStripedPalette()
  166. {
  167.   // 'black out' all 16 palette entries...
  168.   fill_solid( currentPalette, 16, CRGB::Black);
  169.   // and set every fourth one to white.
  170.   currentPalette[0] = CRGB::White;
  171.   currentPalette[4] = CRGB::White;
  172.   currentPalette[8] = CRGB::White;
  173.   currentPalette[12] = CRGB::White;
  174. }
  175. // This function sets up a palette of purple and green stripes.
  176. void SetupPurpleAndGreenPalette()
  177. {
  178.   CRGB purple = CHSV( HUE_PURPLE, 255, 255);
  179.   CRGB green  = CHSV( HUE_GREEN, 255, 255);
  180.   CRGB black  = CRGB::Black;
  181.   
  182.   currentPalette = CRGBPalette16(
  183.     green,  green,  black,  black,
  184.     purple, purple, black,  black,
  185.     green,  green,  black,  black,
  186.     purple, purple, black,  black );
  187. }
  188. //
  189. // Mark's xy coordinate mapping code.  See the XYMatrix for more information on it.
  190. //
  191. uint16_t XY( uint8_t x, uint8_t y)
  192. {
  193.   uint16_t i;
  194.   if( kMatrixSerpentineLayout == false) {
  195.     i = (y * kMatrixWidth) + x;
  196.   }
  197.   if( kMatrixSerpentineLayout == true) {
  198.     if( y & 0x01) {
  199.       // Odd rows run backwards
  200.       uint8_t reverseX = (kMatrixWidth - 1) - x;
  201.       i = (y * kMatrixWidth) + reverseX;
  202.     } else {
  203.       // Even rows run forwards
  204.       i = (y * kMatrixWidth) + x;
  205.     }
  206.   }
  207.   return i;
  208. }
复制代码


回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 17:07:51

回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 17:09:19

  【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  实验程序十八:三速七彩风火轮

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序十八:三速七彩风火轮
  5. */
  6. #include <Adafruit_NeoPixel.h>
  7. #define LED_PIN    6
  8. #define LED_COUNT 24
  9. Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
  10. void setup() {
  11.   strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
  12.   strip.show();            // Turn OFF all pixels ASAP
  13.   strip.setBrightness(30); // Set BRIGHTNESS to about 1/5 (max = 255)
  14. }
  15. void loop() {
  16.   theaterChaseTwo(strip.Color(127, 127, 127), 100);  // set brightness to 100
  17.   theaterChaseTwo(strip.Color(255, 255, 0), 100);
  18.   theaterChaseTwo(strip.Color(127, 0, 0), 100);
  19.   theaterChaseTwo(strip.Color(0, 255, 0), 100);
  20.   theaterChaseTwo(strip.Color(0, 0, 127), 100);
  21.   theaterChaseTwo(strip.Color(143, 0, 255), 100);
  22.   theaterChase(strip.Color(127, 127, 127), 50); // 50 = half brightness
  23.   theaterChase(strip.Color(255, 255, 0), 50);
  24.   theaterChase(strip.Color(127,   0,   0), 50);
  25.   theaterChase(strip.Color(  0, 255,   0), 50);
  26.   theaterChase(strip.Color(  0,   0, 127), 50);
  27.   theaterChase(strip.Color(143, 0, 255), 50);
  28.   
  29.   theaterChase(strip.Color(127, 127, 127), 25); // set brightness to 25
  30.   theaterChase(strip.Color(255, 255, 0), 25);
  31.   theaterChase(strip.Color(127,   0,   0), 25);
  32.   theaterChase(strip.Color(  0, 255,   0), 25);
  33.   theaterChase(strip.Color(  0,   0, 127), 25);
  34.   theaterChase(strip.Color(143, 0, 255), 25);  
  35.   
  36. }
  37. void theaterChase(uint32_t color, int wait) {
  38.   for(int a=0; a<10; a++) {  
  39.     for(int b=0; b<3; b++) {
  40.       strip.clear();         
  41.      
  42.       for(int c=b; c<strip.numPixels(); c += 3) {
  43.         strip.setPixelColor(c, color);
  44.       }
  45.       strip.show();
  46.       delay(wait);  
  47.     }
  48.   }}
  49.   
  50.   void theaterChaseTwo(uint32_t color, int wait) {
  51.   for(int a=0; a<5; a++) {  
  52.     for(int b=0; b<4; b++) {
  53.       strip.clear();        
  54.       
  55.       for(int c=b; c<strip.numPixels(); c += 3) {
  56.         strip.setPixelColor(c, color);
  57.       }
  58.       strip.show();
  59.       delay(wait);  
  60.     }
  61.   }}
  62.   
  63.   void theaterChaseThree(uint32_t color, int wait) {
  64.   for(int a=0; a<10; a++) {  
  65.     for(int b=0; b<2; b++) {
  66.       strip.clear();         
  67.       
  68.       for(int c=b; c<strip.numPixels(); c += 3) {
  69.         strip.setPixelColor(c, color);
  70.       }
  71.       strip.show();
  72.       delay(wait);
  73.     }
  74.   }}
复制代码


回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-17 17:11:31

实验场景图

【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带图1
回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-18 09:13:43

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序十九:八种模式的LED闪烁效果

  1. /*
  2. 【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3. 实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4. 实验程序十九:八种模式的LED闪烁效果
  5. */
  6. #include <Adafruit_NeoPixel.h>
  7. #include <FastLED.h>
  8. #include <EEPROM.h>
  9. #define PIN 6
  10. #define N_PIXELS  24
  11. #define BG 0
  12. #define COLOR_ORDER GRB  // Try mixing up the letters (RGB, GBR, BRG, etc) for a whole new world of color combinations
  13. #define BRIGHTNESS 50   // 0-255, higher number is brighter.
  14. #define LED_TYPE WS2812B
  15. #define MIC_PIN   A4  // Microphone is attached to this analog pin
  16. #define DC_OFFSET  10  // DC offset in mic signal - if unusure, leave 0
  17. #define NOISE     10  // Noise/hum/interference in mic signal
  18. #define SAMPLES   60  // Length of buffer for dynamic level adjustment
  19. #define TOP       (N_PIXELS + 2) // Allow dot to go slightly off scale
  20. #define PEAK_FALL 20  // Rate of peak falling dot
  21. #define N_PIXELS_HALF (N_PIXELS/2)
  22. #define GRAVITY           -9.81              // Downward (negative) acceleration of gravity in m/s^2
  23. #define h0                1                  // Starting height, in meters, of the ball (strip length)
  24. #define NUM_BALLS         3                  // Number of bouncing balls you want (recommend < 7, but 20 is fun in its own way)
  25. #define SPEED .20       // Amount to increment RGB color by each cycle
  26. int brightnessPin = A0, potPin = A1;
  27. //config for balls
  28. float h[NUM_BALLS] ;                         // An array of heights
  29. float vImpact0 = sqrt( -2 * GRAVITY * h0 );  // Impact velocity of the ball when it hits the ground if "dropped" from the top of the strip
  30. float vImpact[NUM_BALLS] ;                   // As time goes on the impact velocity will change, so make an array to store those values
  31. float tCycle[NUM_BALLS] ;                    // The time since the last time the ball struck the ground
  32. int   pos[NUM_BALLS] ;                       // The integer position of the dot on the strip (LED index)
  33. long  tLast[NUM_BALLS] ;                     // The clock time of the last ground strike
  34. float COR[NUM_BALLS] ;                       // Coefficient of Restitution (bounce damping)
  35. float
  36.   greenOffset = 30,
  37.   blueOffset = 150;
  38. byte
  39.   peak      = 0,      // Used for falling dot
  40.   dotCount  = 0,      // Frame counter for delaying dot-falling speed
  41.   volCount  = 0;      // Frame counter for storing past volume data
  42. int
  43.   vol[SAMPLES],       // Collection of prior volume samples
  44.   lvl       = 10,      // Current "dampened" audio level
  45.   minLvlAvg = 0,      // For dynamic adjustment of graph low & high
  46.   maxLvlAvg = 512;
  47.   int brightnessValue, prevBrightnessValue;
  48. int sensorDeviationBrightness = 1;
  49. int sensitivityValue = 128;                               // 0 - 255, initial value (value read from the potentiometer if useSensorValues = true)
  50. int maxSensitivity = 2 * 255;                             // let the 'volume' go up to 200%!
  51. int ledBrightness = 255;                                   // 0 - 255, initial value (value read from the potentiometer if useSensorValues = true)
  52. int val;
  53. Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_PIXELS, PIN, NEO_GRB + NEO_KHZ800);
  54. // FOR SYLON ETC
  55. uint8_t thisbeat =  23;
  56. uint8_t thatbeat =  28;
  57. uint8_t thisfade =   2;                                     // How quickly does it fade? Lower = slower fade rate.
  58. uint8_t thissat = 255;                                     // The saturation, where 255 = brilliant colours.
  59. uint8_t thisbri = 255;
  60. //FOR JUGGLE
  61. uint8_t numdots = 4;                                          // Number of dots in use.
  62. uint8_t faderate = 2;                                         // How long should the trails be. Very low value = longer trails.
  63. uint8_t hueinc = 16;                                          // Incremental change in hue between each dot.
  64. uint8_t thishue = 0;                                          // Starting hue.
  65. uint8_t curhue = 0;
  66. uint8_t thisbright = 255;                                     // How bright should the LED/display be.
  67. uint8_t basebeat = 5;
  68. uint8_t max_bright = 255;
  69. // Twinkle
  70. float redStates[N_PIXELS];
  71. float blueStates[N_PIXELS];
  72. float greenStates[N_PIXELS];
  73. float Fade = 0.96;
  74. // Vu meter 4
  75. const uint32_t Red = strip.Color(255, 0, 0);
  76. const uint32_t Yellow = strip.Color(255, 255, 0);
  77. const uint32_t Green = strip.Color(0, 255, 0);
  78. const uint32_t Blue = strip.Color(0, 0, 255);
  79. const uint32_t White = strip.Color(255, 255, 255);
  80. const uint32_t Dark = strip.Color(0, 0, 0);
  81. unsigned int sample;
  82. CRGB leds[N_PIXELS];
  83. int          myhue =   0;
  84. // constants used here to set pin numbers:
  85. const int buttonPin = 3;     // the number of the pushbutton pin
  86. // Variables will change:
  87. int buttonPushCounter = 0;   // counter for the number of button presses
  88. int buttonState = 0;         // current state of the button
  89. int lastButtonState = 0;
  90. //Ripple variables
  91. int color;
  92. int center = 0;
  93. int step = -1;
  94. int maxSteps = 8;
  95. float fadeRate = 0.80;
  96. int diff;
  97. //background color
  98. uint32_t currentBg = random(256);
  99. uint32_t nextBg = currentBg;
  100. void setup() {
  101.   delay( 2000 ); // power-up safety delay
  102.   FastLED.addLeds<WS2812B, PIN, COLOR_ORDER>(leds, N_PIXELS).setCorrection( TypicalLEDStrip );
  103.   FastLED.setBrightness(  BRIGHTNESS );
  104.   analogReference(EXTERNAL);
  105.   memset(vol, 0, sizeof(vol));
  106.   LEDS.addLeds<LED_TYPE, PIN, COLOR_ORDER>(leds, N_PIXELS);
  107.   strip.begin();
  108.   strip.show(); // Initialize all pixels to 'off'
  109.   
  110.    
  111.   //initialize the serial port
  112.   Serial.begin(115200);
  113.    pinMode(buttonPin, INPUT);  
  114.     pinMode(2, OUTPUT);
  115.   //initialize the buttonPin as output
  116. digitalWrite(buttonPin, HIGH);
  117. digitalWrite(2, HIGH);
  118. for (int i = 0 ; i < NUM_BALLS ; i++) {    // Initialize variables
  119.     tLast[i] = millis();
  120.     h[i] = h0;
  121.     pos[i] = 0;                              // Balls start on the ground
  122.     vImpact[i] = vImpact0;                   // And "pop" up at vImpact0
  123.     tCycle[i] = 0;
  124.     COR[i] = 0.90 - float(i)/pow(NUM_BALLS,2);
  125.   }
  126. }
  127. void loop() {
  128.    brightnessValue = analogRead(brightnessPin);
  129.   brightnessValue = map(brightnessValue, 0, 1023, 0, 255);
  130.   
  131.   if (abs(brightnessValue - prevBrightnessValue) > sensorDeviationBrightness) {
  132.     ledBrightness = brightnessValue;
  133.     strip.setBrightness(ledBrightness);
  134.     prevBrightnessValue = brightnessValue;
  135.   }
  136.   
  137.    //for mic
  138.   uint8_t  i;
  139.   uint16_t minLvl, maxLvl;
  140.   int      n, height;
  141.   // end mic
  142.   buttonPushCounter=EEPROM.read(0);
  143.   // read the pushbutton input pin:
  144.   buttonState = digitalRead(buttonPin);
  145.     // compare the buttonState to its previous state
  146.   if (buttonState != lastButtonState) {
  147.     // if the state has changed, increment the counter
  148.     if (buttonState == HIGH) {
  149.       // if the current state is HIGH then the button
  150.       // wend from off to on:
  151.       buttonPushCounter++;
  152.       Serial.println("on");
  153.       Serial.print("number of button pushes:  ");
  154.       Serial.println(buttonPushCounter);
  155.       if(buttonPushCounter>=14) {
  156.       buttonPushCounter=1;}
  157.       EEPROM.write(0,buttonPushCounter);
  158.       
  159.     }
  160.     else {
  161.       // if the current state is LOW then the button
  162.       // wend from on to off:
  163.       Serial.println("off");
  164.     }
  165.   }
  166.   // save the current state as the last state,
  167.   //for next time through the loop
  168.   
  169.   lastButtonState = buttonState;
  170. switch (buttonPushCounter){
  171.          
  172.   case 1:
  173.      buttonPushCounter==1; {
  174.       vu(); // Red
  175.      break;}
  176.       
  177.   case 2:
  178.      buttonPushCounter==2; {
  179.        vu2(); // Red
  180.       break;}
  181.       
  182.    case 3:
  183.      buttonPushCounter==3; {
  184.     Vu3(); //
  185.       break;}
  186.          
  187.     case 4:
  188.      buttonPushCounter==4; {
  189.     Vu4(); //
  190.       break;}  
  191.       
  192.        case 5:
  193.      buttonPushCounter==5; {
  194.       rainbow(150);
  195.        break;}
  196.       
  197.         case 6:
  198.      buttonPushCounter==6; {
  199.       rainbow(20);
  200.        break;}
  201.       
  202.          case 7:
  203.      buttonPushCounter==7; {
  204.       ripple();
  205.        break;}
  206.       
  207.            case 8:
  208.      buttonPushCounter==8; {
  209.       ripple2();
  210.        break;}
  211.       
  212.               case 9:
  213.      buttonPushCounter==9; {
  214.       Twinkle();
  215.        break;}
  216.       
  217.          case 10:
  218.      buttonPushCounter==10; {
  219.       pattern2();
  220.        break;}
  221.       
  222.            case 11:
  223.      buttonPushCounter==11; {
  224.       pattern3();
  225.        break;}
  226.       
  227.            case 12:
  228.      buttonPushCounter==12; {
  229.     Balls(); //
  230.       break;}   
  231.       
  232.         case 13:
  233.      buttonPushCounter==13; {
  234.     colorWipe(strip.Color(0, 0, 0), 10); // A Black
  235.       break;}
  236.          
  237.    }
  238. }
  239. void colorWipe(uint32_t c, uint8_t wait) {
  240.   for(uint16_t i=0; i<strip.numPixels(); i++) {
  241.       strip.setPixelColor(i, c);
  242.       strip.show();
  243.       if (digitalRead(buttonPin) != lastButtonState)  // <------------- add this
  244.        return;         // <------------ and this
  245.       delay(wait);
  246.   }
  247. }
  248. void Vu4() {
  249.     uint8_t  i;
  250.   uint16_t minLvl, maxLvl;
  251.   int      n, height;
  252.   
  253.   val = (analogRead(potPin));  
  254.   val= map(val, 0, 1023, -10, 6);
  255.   
  256.   n   = analogRead(MIC_PIN);                        // Raw reading from mic
  257.   n   = abs(n - 0 - DC_OFFSET); // Center on zero
  258.   n   = (n <= NOISE) ? 0 : (n - NOISE);             // Remove noise/hum
  259.   
  260.     if(val<0){
  261.         n=n/(val*(-1));
  262.         }
  263.        if(val>0){
  264.         n=n*val;
  265.         }
  266.   
  267.   lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)
  268.   // Calculate bar height based on dynamic min/max levels (fixed point):
  269.   height = TOP * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);
  270.   if(height < 0L)       height = 0;      // Clip output
  271.   else if(height > TOP) height = TOP;
  272.   if(height > peak)     peak   = height; // Keep 'peak' dot at top
  273.   greenOffset += SPEED;
  274.   blueOffset += SPEED;
  275.   if (greenOffset >= 255) greenOffset = 0;
  276.   if (blueOffset >= 255) blueOffset = 0;
  277.   // Color pixels based on rainbow gradient
  278.   for(i=0; i<N_PIXELS_HALF; i++) {
  279.     if(i >= height) {              
  280.       strip.setPixelColor(N_PIXELS_HALF-i-1,   0,   0, 0);
  281.       strip.setPixelColor(N_PIXELS_HALF+i,   0,   0, 0);
  282.     }
  283.     else {
  284.       uint32_t color = Wheel(map(i,0,N_PIXELS_HALF-1,(int)greenOffset, (int)blueOffset));
  285.       strip.setPixelColor(N_PIXELS_HALF-i-1,color);
  286.       strip.setPixelColor(N_PIXELS_HALF+i,color);
  287.     }
  288.    
  289.   }
  290.   // Draw peak dot  
  291.   if(peak > 0 && peak <= N_PIXELS_HALF-1) {
  292.     uint32_t color = Wheel(map(peak,0,N_PIXELS_HALF-1,30,150));
  293.     strip.setPixelColor(N_PIXELS_HALF-peak-1,color);
  294.     strip.setPixelColor(N_PIXELS_HALF+peak,color);
  295.   }
  296.   
  297.    strip.show(); // Update strip
  298. // Every few frames, make the peak pixel drop by 1:
  299.     if(++dotCount >= PEAK_FALL) { //fall rate
  300.       
  301.       if(peak > 0) peak--;
  302.       dotCount = 0;
  303.     }
  304.   vol[volCount] = n;                      // Save sample for dynamic leveling
  305.   if(++volCount >= SAMPLES) volCount = 0; // Advance/rollover sample counter
  306.   // Get volume range of prior frames
  307.   minLvl = maxLvl = vol[0];
  308.   for(i=1; i<SAMPLES; i++) {
  309.     if(vol[i] < minLvl)      minLvl = vol[i];
  310.     else if(vol[i] > maxLvl) maxLvl = vol[i];
  311.   }
  312.   // minLvl and maxLvl indicate the volume range over prior frames, used
  313.   // for vertically scaling the output graph (so it looks interesting
  314.   // regardless of volume level).  If they're too close together though
  315.   // (e.g. at very low volume levels) the graph becomes super coarse
  316.   // and 'jumpy'...so keep some minimum distance between them (this
  317.   // also lets the graph go to zero when no sound is playing):
  318.   if((maxLvl - minLvl) < TOP) maxLvl = minLvl + TOP;
  319.   minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
  320.   maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)
  321. }
  322. void Vu3() {
  323.   uint8_t i;
  324.   uint16_t minLvl, maxLvl;
  325.   int n, height;
  326.   val = (analogRead(potPin));  
  327.   val= map(val, 0, 1023, -10, 6);
  328.   n = analogRead(MIC_PIN);             // Raw reading from mic
  329.   n = abs(n - 0 - DC_OFFSET);        // Center on zero
  330.   n = (n <= NOISE) ? 0 : (n - NOISE);  // Remove noise/hum
  331.       if(val<0){
  332.         n=n/(val*(-1));
  333.         }
  334.        if(val>0){
  335.         n=n*val;
  336.         }
  337.         
  338.   lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)
  339.   // Calculate bar height based on dynamic min/max levels (fixed point):
  340.   height = TOP * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);
  341.   if (height < 0L)       height = 0;      // Clip output
  342.   else if (height > TOP) height = TOP;
  343.   if (height > peak)     peak   = height; // Keep 'peak' dot at top
  344.   greenOffset += SPEED;
  345.   blueOffset += SPEED;
  346.   if (greenOffset >= 255) greenOffset = 0;
  347.   if (blueOffset >= 255) blueOffset = 0;
  348.   // Color pixels based on rainbow gradient
  349.   for (i = 0; i < N_PIXELS; i++) {
  350.     if (i >= height) {
  351.       strip.setPixelColor(i, 0, 0, 0);
  352.     } else {
  353.       strip.setPixelColor(i, Wheel(
  354.         map(i, 0, strip.numPixels() - 1, (int)greenOffset, (int)blueOffset)
  355.       ));
  356.     }
  357.   }
  358.   // Draw peak dot  
  359.   if(peak > 0 && peak <= N_PIXELS-1) strip.setPixelColor(peak,Wheel(map(peak,0,strip.numPixels()-1,30,150)));
  360.   
  361.    strip.show(); // Update strip
  362. // Every few frames, make the peak pixel drop by 1:
  363.     if(++dotCount >= PEAK_FALL) { //fall rate
  364.       
  365.       if(peak > 0) peak--;
  366.       dotCount = 0;
  367.     }
  368.   strip.show();  // Update strip
  369.   vol[volCount] = n;
  370.   if (++volCount >= SAMPLES) {
  371.     volCount = 0;
  372.   }
  373.   // Get volume range of prior frames
  374.   minLvl = maxLvl = vol[0];
  375.   for (i = 1; i < SAMPLES; i++) {
  376.     if (vol[i] < minLvl) {
  377.       minLvl = vol[i];
  378.     } else if (vol[i] > maxLvl) {
  379.       maxLvl = vol[i];
  380.     }
  381.   }
  382.   // minLvl and maxLvl indicate the volume range over prior frames, used
  383.   // for vertically scaling the output graph (so it looks interesting
  384.   // regardless of volume level).  If they're too close together though
  385.   // (e.g. at very low volume levels) the graph becomes super coarse
  386.   // and 'jumpy'...so keep some minimum distance between them (this
  387.   // also lets the graph go to zero when no sound is playing):
  388.   if ((maxLvl - minLvl) < TOP) {
  389.     maxLvl = minLvl + TOP;
  390.   }
  391.   minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
  392.   maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)
  393. }
  394. void Balls() {
  395.   for (int i = 0 ; i < NUM_BALLS ; i++) {
  396.     tCycle[i] =  millis() - tLast[i] ;     // Calculate the time since the last time the ball was on the ground
  397.     // A little kinematics equation calculates positon as a function of time, acceleration (gravity) and intial velocity
  398.     h[i] = 0.5 * GRAVITY * pow( tCycle[i]/1000 , 2.0 ) + vImpact[i] * tCycle[i]/1000;
  399.     if ( h[i] < 0 ) {                     
  400.       h[i] = 0;                            // If the ball crossed the threshold of the "ground," put it back on the ground
  401.       vImpact[i] = COR[i] * vImpact[i] ;   // and recalculate its new upward velocity as it's old velocity * COR
  402.       tLast[i] = millis();
  403.       if ( vImpact[i] < 0.01 ) vImpact[i] = vImpact0;  // If the ball is barely moving, "pop" it back up at vImpact0
  404.     }
  405.     pos[i] = round( h[i] * (N_PIXELS - 1) / h0);       // Map "h" to a "pos" integer index position on the LED strip
  406.   }
  407.   //Choose color of LEDs, then the "pos" LED on
  408.   for (int i = 0 ; i < NUM_BALLS ; i++) leds[pos[i]] = CHSV( uint8_t (i * 40) , 255, 255);
  409.   FastLED.show();
  410.   //Then off for the next loop around
  411.   for (int i = 0 ; i < NUM_BALLS ; i++) {
  412.     leds[pos[i]] = CRGB::Black;
  413.   }
  414. }
  415. // Slightly different, this makes the rainbow equally distributed throughout
  416. void rainbowCycle(uint8_t wait) {
  417.   uint16_t i, j;
  418.   for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
  419.     for(i=0; i< strip.numPixels(); i++) {
  420.       strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
  421.     }
  422.     strip.show();
  423.      if (digitalRead(buttonPin) != lastButtonState)  // <------------- add this
  424.        return;         // <------------ and this
  425.       delay(wait);
  426.         }
  427.     }
  428. // HERE
  429. void vu() {
  430.   uint8_t  i;
  431.   uint16_t minLvl, maxLvl;
  432.   int      n, height;
  433.   val = (analogRead(potPin));  
  434.   val= map(val, 0, 1023, -10, 6);
  435.   
  436.   n   = analogRead(MIC_PIN);                        // Raw reading from mic
  437.   n   = abs(n - 0 - DC_OFFSET); // Center on zero
  438.   n   = (n <= NOISE) ? 0 : (n - NOISE);             // Remove noise/hum
  439.      if(val<0){
  440.         n=n/(val*(-1));
  441.         }
  442.        if(val>0){
  443.         n=n*val;
  444.         }
  445.   lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)
  446.   // Calculate bar height based on dynamic min/max levels (fixed point):
  447.   height = TOP * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);
  448.   if(height < 0L)       height = 0;      // Clip output
  449.   else if(height > TOP) height = TOP;
  450.   if(height > peak)     peak   = height; // Keep 'peak' dot at top
  451.   // Color pixels based on rainbow gradient
  452.   for(i=0; i<N_PIXELS; i++) {
  453.     if(i >= height)               strip.setPixelColor(i,   0,   0, 0);
  454.     else strip.setPixelColor(i,Wheel(map(i,0,strip.numPixels()-1,30,150)));   
  455.   }
  456.   // Draw peak dot  
  457.   if(peak > 0 && peak <= N_PIXELS-1) strip.setPixelColor(peak,Wheel(map(peak,0,strip.numPixels()-1,30,150)));
  458.   
  459.    strip.show(); // Update strip
  460. // Every few frames, make the peak pixel drop by 1:
  461.     if(++dotCount >= PEAK_FALL) { //fall rate
  462.       
  463.       if(peak > 0) peak--;
  464.       dotCount = 0;
  465.     }
  466.   vol[volCount] = n;                      // Save sample for dynamic leveling
  467.   if(++volCount >= SAMPLES) volCount = 0; // Advance/rollover sample counter
  468.   // Get volume range of prior frames
  469.   minLvl = maxLvl = vol[0];
  470.   for(i=1; i<SAMPLES; i++) {
  471.     if(vol[i] < minLvl)      minLvl = vol[i];
  472.     else if(vol[i] > maxLvl) maxLvl = vol[i];
  473.   }
  474.   // minLvl and maxLvl indicate the volume range over prior frames, used
  475.   // for vertically scaling the output graph (so it looks interesting
  476.   // regardless of volume level).  If they're too close together though
  477.   // (e.g. at very low volume levels) the graph becomes super coarse
  478.   // and 'jumpy'...so keep some minimum distance between them (this
  479.   // also lets the graph go to zero when no sound is playing):
  480.   if((maxLvl - minLvl) < TOP) maxLvl = minLvl + TOP;
  481.   minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
  482.   maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)
  483. }
  484. // Input a value 0 to 255 to get a color value.
  485. // The colors are a transition r - g - b - back to r.
  486. uint32_t Wheel(byte WheelPos) {
  487.   if(WheelPos < 85) {
  488.    return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
  489.   } else if(WheelPos < 170) {
  490.    WheelPos -= 85;
  491.    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  492.   } else {
  493.    WheelPos -= 170;
  494.    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  495.   }
  496. }
  497. void vu2() {
  498.   
  499.   uint8_t  i;
  500.   uint16_t minLvl, maxLvl;
  501.   int      n, height;
  502.   val = (analogRead(potPin));  
  503.   val= map(val, 0, 1023, -10, 6);
  504.   n   = analogRead(MIC_PIN);                        // Raw reading from mic
  505.   n   = abs(n - 0 - DC_OFFSET); // Center on zero
  506.   n   = (n <= NOISE) ? 0 : (n - NOISE);             // Remove noise/hum
  507.       if(val<0){
  508.         n=n/(val*(-1));
  509.         }
  510.        if(val>0){
  511.         n=n*val;
  512.         }
  513.   lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)
  514.   // Calculate bar height based on dynamic min/max levels (fixed point):
  515.   height = TOP * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);
  516.   if(height < 0L)       height = 0;      // Clip output
  517.   else if(height > TOP) height = TOP;
  518.   if(height > peak)     peak   = height; // Keep 'peak' dot at top
  519.   // Color pixels based on rainbow gradient
  520.   for(i=0; i<N_PIXELS_HALF; i++) {
  521.     if(i >= height) {              
  522.       strip.setPixelColor(N_PIXELS_HALF-i-1,   0,   0, 0);
  523.       strip.setPixelColor(N_PIXELS_HALF+i,   0,   0, 0);
  524.     }
  525.     else {
  526.       uint32_t color = Wheel(map(i,0,N_PIXELS_HALF-1,30,150));
  527.       strip.setPixelColor(N_PIXELS_HALF-i-1,color);
  528.       strip.setPixelColor(N_PIXELS_HALF+i,color);
  529.     }  
  530.   }
  531.   // Draw peak dot  
  532.   if(peak > 0 && peak <= N_PIXELS_HALF-1) {
  533.     uint32_t color = Wheel(map(peak,0,N_PIXELS_HALF-1,30,150));
  534.     strip.setPixelColor(N_PIXELS_HALF-peak-1,color);
  535.     strip.setPixelColor(N_PIXELS_HALF+peak,color);
  536.   }
  537.   
  538.    strip.show(); // Update strip
  539. // Every few frames, make the peak pixel drop by 1:
  540.     if(++dotCount >= PEAK_FALL) { //fall rate
  541.       
  542.       if(peak > 0) peak--;
  543.       dotCount = 0;
  544.     }
  545.   vol[volCount] = n;                      // Save sample for dynamic leveling
  546.   if(++volCount >= SAMPLES) volCount = 0; // Advance/rollover sample counter
  547.   // Get volume range of prior frames
  548.   minLvl = maxLvl = vol[0];
  549.   for(i=1; i<SAMPLES; i++) {
  550.     if(vol[i] < minLvl)      minLvl = vol[i];
  551.     else if(vol[i] > maxLvl) maxLvl = vol[i];
  552.   }
  553.   // minLvl and maxLvl indicate the volume range over prior frames, used
  554.   // for vertically scaling the output graph (so it looks interesting
  555.   // regardless of volume level).  If they're too close together though
  556.   // (e.g. at very low volume levels) the graph becomes super coarse
  557.   // and 'jumpy'...so keep some minimum distance between them (this
  558.   // also lets the graph go to zero when no sound is playing):
  559.   if((maxLvl - minLvl) < TOP) maxLvl = minLvl + TOP;
  560.   minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
  561.   maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)
  562. }
  563. //here................
  564. void ripple() {
  565.     if (currentBg == nextBg) {
  566.       nextBg = random(256);
  567.     }
  568.     else if (nextBg > currentBg) {
  569.       currentBg++;
  570.     } else {
  571.       currentBg--;
  572.     }
  573.     for(uint16_t l = 0; l < N_PIXELS; l++) {
  574.       leds[l] = CHSV(currentBg, 255, 50);         // strip.setPixelColor(l, Wheel(currentBg, 0.1));
  575.     }
  576.   if (step == -1) {
  577.     center = random(N_PIXELS);
  578.     color = random(256);
  579.     step = 0;
  580.   }
  581.   if (step == 0) {
  582.     leds[center] = CHSV(color, 255, 255);         // strip.setPixelColor(center, Wheel(color, 1));
  583.     step ++;
  584.   }
  585.   else {
  586.     if (step < maxSteps) {
  587.       Serial.println(pow(fadeRate,step));
  588.       leds[wrap(center + step)] = CHSV(color, 255, pow(fadeRate, step)*255);       //   strip.setPixelColor(wrap(center + step), Wheel(color, pow(fadeRate, step)));
  589.       leds[wrap(center - step)] = CHSV(color, 255, pow(fadeRate, step)*255);       //   strip.setPixelColor(wrap(center - step), Wheel(color, pow(fadeRate, step)));
  590.       if (step > 3) {
  591.         leds[wrap(center + step - 3)] = CHSV(color, 255, pow(fadeRate, step - 2)*255);     //   strip.setPixelColor(wrap(center + step - 3), Wheel(color, pow(fadeRate, step - 2)));
  592.         leds[wrap(center - step + 3)] = CHSV(color, 255, pow(fadeRate, step - 2)*255);     //   strip.setPixelColor(wrap(center - step + 3), Wheel(color, pow(fadeRate, step - 2)));
  593.       }
  594.       step ++;
  595.     }
  596.     else {
  597.       step = -1;
  598.     }
  599.   }
  600.   LEDS.show();
  601.   delay(50);
  602. }
  603. int wrap(int step) {
  604.   if(step < 0) return N_PIXELS + step;
  605.   if(step > N_PIXELS - 1) return step - N_PIXELS;
  606.   return step;
  607. }
  608. void one_color_allHSV(int ahue, int abright) {                // SET ALL LEDS TO ONE COLOR (HSV)
  609.   for (int i = 0 ; i < N_PIXELS; i++ ) {
  610.     leds[i] = CHSV(ahue, 255, abright);
  611.   }
  612. }
  613. void ripple2() {
  614.   if (BG){
  615.     if (currentBg == nextBg) {
  616.       nextBg = random(256);
  617.     }
  618.     else if (nextBg > currentBg) {
  619.       currentBg++;
  620.     } else {
  621.       currentBg--;
  622.     }
  623.     for(uint16_t l = 0; l < N_PIXELS; l++) {
  624.       strip.setPixelColor(l, Wheel(currentBg, 0.1));
  625.     }
  626.   } else {
  627.     for(uint16_t l = 0; l < N_PIXELS; l++) {
  628.       strip.setPixelColor(l, 0, 0, 0);
  629.     }
  630.   }
  631.   if (step == -1) {
  632.     center = random(N_PIXELS);
  633.     color = random(256);
  634.     step = 0;
  635.   }
  636.   if (step == 0) {
  637.     strip.setPixelColor(center, Wheel(color, 1));
  638.     step ++;
  639.   }
  640.   else {
  641.     if (step < maxSteps) {
  642.       strip.setPixelColor(wrap(center + step), Wheel(color, pow(fadeRate, step)));
  643.       strip.setPixelColor(wrap(center - step), Wheel(color, pow(fadeRate, step)));
  644.       if (step > 3) {
  645.         strip.setPixelColor(wrap(center + step - 3), Wheel(color, pow(fadeRate, step - 2)));
  646.         strip.setPixelColor(wrap(center - step + 3), Wheel(color, pow(fadeRate, step - 2)));
  647.       }
  648.       step ++;
  649.     }
  650.     else {
  651.       step = -1;
  652.     }
  653.   }
  654.   
  655.   strip.show();
  656.   delay(50);
  657. }
  658. //int wrap(int step) {
  659. //  if(step < 0) return Pixels + step;
  660. //  if(step > Pixels - 1) return step - Pixels;
  661. //  return step;
  662. //}
  663. // Input a value 0 to 255 to get a color value.
  664. // The colours are a transition r - g - b - back to r.
  665. uint32_t Wheel(byte WheelPos, float opacity) {
  666.   
  667.   if(WheelPos < 85) {
  668.     return strip.Color((WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity, 0);
  669.   }
  670.   else if(WheelPos < 170) {
  671.     WheelPos -= 85;
  672.     return strip.Color((255 - WheelPos * 3) * opacity, 0, (WheelPos * 3) * opacity);
  673.   }
  674.   else {
  675.     WheelPos -= 170;
  676.     return strip.Color(0, (WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity);
  677.   }
  678. }
  679.    void pattern2() {
  680.       
  681.        sinelon();                                                  // Call our sequence.
  682.   show_at_max_brightness_for_power();                         // Power managed display of LED's.
  683. } // loop()
  684. void sinelon() {
  685.   // a colored dot sweeping back and forth, with fading trails
  686.   fadeToBlackBy( leds, N_PIXELS, thisfade);
  687.   int pos1 = beatsin16(thisbeat,0,N_PIXELS);
  688.   int pos2 = beatsin16(thatbeat,0,N_PIXELS);
  689.     leds[(pos1+pos2)/2] += CHSV( myhue++/64, thissat, thisbri);
  690. }
  691. // Pattern 3 - JUGGLE
  692.     void pattern3() {
  693.        ChangeMe();
  694.   juggle();
  695.   show_at_max_brightness_for_power();                         // Power managed display of LED's.
  696. } // loop()
  697. void juggle() {                                               // Several colored dots, weaving in and out of sync with each other
  698.   curhue = thishue;                                          // Reset the hue values.
  699.   fadeToBlackBy(leds, N_PIXELS, faderate);
  700.   for( int i = 0; i < numdots; i++) {
  701.     leds[beatsin16(basebeat+i+numdots,0,N_PIXELS)] += CHSV(curhue, thissat, thisbright);   //beat16 is a FastLED 3.1 function
  702.     curhue += hueinc;
  703.   }
  704. } // juggle()
  705. void ChangeMe() {                                             // A time (rather than loop) based demo sequencer. This gives us full control over the length of each sequence.
  706.   uint8_t secondHand = (millis() / 1000) % 30;                // IMPORTANT!!! Change '30' to a different value to change duration of the loop.
  707.   static uint8_t lastSecond = 99;                             // Static variable, means it's only defined once. This is our 'debounce' variable.
  708.   if (lastSecond != secondHand) {                             // Debounce to make sure we're not repeating an assignment.
  709.     lastSecond = secondHand;
  710.     if (secondHand ==  0)  {numdots=1; faderate=2;}  // You can change values here, one at a time , or altogether.
  711.     if (secondHand == 10)  {numdots=4; thishue=128; faderate=8;}
  712.     if (secondHand == 20)  {hueinc=48; thishue=random8();}                               // Only gets called once, and not continuously for the next several seconds. Therefore, no rainbows.
  713.   }
  714. } // ChangeMe()
  715. void Twinkle () {
  716.    if (random(25) == 1) {
  717.       uint16_t i = random(N_PIXELS);
  718.       if (redStates[i] < 1 && greenStates[i] < 1 && blueStates[i] < 1) {
  719.         redStates[i] = random(256);
  720.         greenStates[i] = random(256);
  721.         blueStates[i] = random(256);
  722.       }
  723.     }
  724.    
  725.     for(uint16_t l = 0; l < N_PIXELS; l++) {
  726.       if (redStates[l] > 1 || greenStates[l] > 1 || blueStates[l] > 1) {
  727.         strip.setPixelColor(l, redStates[l], greenStates[l], blueStates[l]);
  728.         
  729.         if (redStates[l] > 1) {
  730.           redStates[l] = redStates[l] * Fade;
  731.         } else {
  732.           redStates[l] = 0;
  733.         }
  734.         
  735.         if (greenStates[l] > 1) {
  736.           greenStates[l] = greenStates[l] * Fade;
  737.         } else {
  738.           greenStates[l] = 0;
  739.         }
  740.         
  741.         if (blueStates[l] > 1) {
  742.           blueStates[l] = blueStates[l] * Fade;
  743.         } else {
  744.           blueStates[l] = 0;
  745.         }
  746.         
  747.       } else {
  748.         strip.setPixelColor(l, 0, 0, 0);
  749.       }
  750.     }
  751.     strip.show();
  752.      delay(10);
  753.   
  754. }
  755. // TOO HERE
  756. void rainbow(uint8_t wait) {
  757.   uint16_t i, j;
  758.   for(j=0; j<256; j++) {
  759.     for(i=0; i<strip.numPixels(); i++) {
  760.       strip.setPixelColor(i, Wheel((i+j) & 255));
  761.     }
  762.     strip.show();
  763.     // check if a button pressed
  764.     if (digitalRead(buttonPin) != lastButtonState)  // <------------- add this
  765.        return;         // <------------ and this
  766.     delay(wait);
  767.   }
  768. }
复制代码


回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-18 09:31:21

实验场景图  动态图

【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带图1
回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-18 10:49:58

实验串口返回情况(可以监视不同模式的转换)

【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带图1

回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-18 18:32:30

  【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  实验程序二十:外部声音触发(阙值可调整)动态节奏灯带

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序二十:外部声音触发(阙值可调整)动态节奏灯带
  5. */
  6. #include <WS2812FX.h>
  7. #define LED_COUNT 24
  8. #define LED_PIN 6
  9. #define ANALOG_PIN A0
  10. #define ANALOG_THRESHOLD 512
  11. #define TIMER_MS 3000
  12. WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_RGB + NEO_KHZ800);
  13. unsigned long last_trigger = 0;
  14. unsigned long now = 0;
  15. void setup() {
  16.   ws2812fx.init();
  17.   ws2812fx.setBrightness(33);
  18.   ws2812fx.setMode(FX_MODE_RANDOM_COLOR);
  19. }
  20. void loop() {
  21.   now = millis();
  22.   ws2812fx.service();
  23.   if(now - last_trigger > TIMER_MS) {
  24.     ws2812fx.trigger();
  25.     last_trigger = now;
  26.   }
  27.   if(analogRead(ANALOG_PIN) > ANALOG_THRESHOLD) {
  28.     ws2812fx.trigger();
  29.   }
  30. }
复制代码


回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-18 19:15:07

实验场景图  动态图

【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带图1
回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-18 19:18:06

回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-20 15:26:30

  【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  实验程序二十一:MegunoLink音乐反应式24颗LED灯带

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序二十一:MegunoLink音乐反应式24颗LED灯带
  5. */
  6. #include<FastLED.h>
  7. #include<MegunoLink.h>
  8. #include<Filter.h>
  9. // define necessary parameters
  10. #define N_PIXELS  24
  11. #define MIC_PIN   A0
  12. #define LED_PIN   D6 // labeled "D6" on the board
  13. // the following parameters can be tweaked according to your audio levels
  14. #define NOISE 50
  15. #define TOP   (N_PIXELS+2) // allow the max level to be slightly off scale
  16. #define LED_TYPE  WS2811
  17. #define BRIGHTNESS  18     // a little dim for recording purposes
  18. #define COLOR_ORDER GRB
  19. // declare the LED array
  20. CRGB leds[N_PIXELS];
  21. // define the variables needed for the audio levels
  22. int lvl = 0, minLvl = 0, maxLvl = 600; // tweak the min and max as needed
  23. // instantiate the filter class for smoothing the raw audio signal
  24. ExponentialFilter<long> ADCFilter(5,0);
  25. void setup() {
  26.   // put your setup code here, to run once:
  27.   Serial.begin(115200);
  28.   // initialize the LED object
  29.   FastLED.addLeds<LED_TYPE,LED_PIN,COLOR_ORDER>(leds,N_PIXELS).setCorrection(TypicalLEDStrip);
  30.   FastLED.setBrightness(BRIGHTNESS);
  31. }
  32. void loop() {
  33.   // put your main code here, to run repeatedly:
  34.   // read the audio signal and filter it
  35.   int n, height;
  36.   n = analogRead(MIC_PIN);
  37.   // remove the MX9614 bias of 1.25VDC
  38.   n = abs(1023 - n);
  39.   // hard limit noise/hum
  40.   n = (n <= NOISE) ? 0 : abs(n - NOISE);
  41.   // apply the exponential filter to smooth the raw signal
  42.   ADCFilter.Filter(n);
  43.   lvl = ADCFilter.Current();
  44. //  // plot the raw versus filtered signals
  45. //  Serial.print(n);
  46. //  Serial.print(" ");
  47. //  Serial.println(lvl);
  48.   // calculate the number of pixels as a percentage of the range
  49.   // TO-DO: can be done dynamically by using a running average of min/max audio levels
  50.   height = TOP * (lvl - minLvl) / (long)(maxLvl - minLvl);
  51.   if(height < 0L) height = 0;
  52.   else if(height > TOP) height = TOP;
  53.   // turn the LEDs corresponding to the level on/off
  54.   for(uint8_t i = 0; i < N_PIXELS; i++) {
  55.     // turn off LEDs above the current level
  56.     if(i >= height) leds[i] = CRGB(0,0,0);
  57.     // otherwise, turn them on!
  58.     else leds[i] = Wheel( map( i, 0, N_PIXELS-1, 30, 150 ) );
  59.   }
  60.   FastLED.show();
  61. }
  62. CRGB Wheel(byte WheelPos) {
  63.   // return a color value based on an input value between 0 and 255
  64.   if(WheelPos < 85)
  65.     return CRGB(WheelPos * 3, 255 - WheelPos * 3, 0);
  66.   else if(WheelPos < 170) {
  67.     WheelPos -= 85;
  68.     return CRGB(255 - WheelPos * 3, 0, WheelPos * 3);
  69.   } else {
  70.     WheelPos -= 170;
  71.     return CRGB(0, WheelPos * 3, 255 - WheelPos * 3);
  72.   }
  73. }
复制代码


回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-20 15:27:53

实验场景图  动态图

【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带图1
回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-7-20 15:31:26

回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-8-12 17:05:23

实验的视频记录(1分49秒)

https://v.youku.com/v_show/id_XN ... hcb.playlsit.page.3



回复

使用道具 举报

驴友花雕  中级技神
 楼主|

发表于 2022-8-12 17:12:28

实验的视频记录(50秒)

https://v.youku.com/v_show/id_XNTg5MzA4Mzc4OA==.html?spm=a2hcb.playlsit.page.1


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4 备案 沪公网安备31011502402448

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail