Arduino爱好者

 找回密码
 立即注册

QQ登录

只需一步,快速开始

楼主: eagler8

[经验] 【Arduino】108种传感器系列实验(89)--- 4*4位 RGB LED 全彩模块

[复制链接]
 楼主| 发表于 2021-9-17 16:19 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  项目二十:每个 LED 灯条的颜色校正设置,以及总输出'色温'的总控制
  实验接线
  Module    UNO
  VCC —— 3.3V
  GND —— GND
  DI  ——  D6

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  3.   实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  4.   项目二十:每个 LED 灯条的颜色校正设置,以及总输出'色温'的总控制
  5.   实验接线
  6.   Module    UNO
  7.   VCC —— 3.3V
  8.   GND —— GND
  9.   DI  ——  D6
  10. */

  11. #include <FastLED.h>
  12. #define LED_PIN     6
  13. // Information about the LED strip itself
  14. #define NUM_LEDS    16
  15. #define CHIPSET     WS2811
  16. #define COLOR_ORDER GRB
  17. CRGB leds[NUM_LEDS];
  18. #define BRIGHTNESS  26

  19. // FastLED v2.1 provides two color-management controls:
  20. //   (1) color correction settings for each LED strip, and
  21. //   (2) master control of the overall output 'color temperature'
  22. //
  23. // THIS EXAMPLE demonstrates the second, "color temperature" control.
  24. // It shows a simple rainbow animation first with one temperature profile,
  25. // and a few seconds later, with a different temperature profile.
  26. //
  27. // The first pixel of the strip will show the color temperature.
  28. //
  29. // HELPFUL HINTS for "seeing" the effect in this demo:
  30. // * Don't look directly at the LED pixels.  Shine the LEDs aganst
  31. //   a white wall, table, or piece of paper, and look at the reflected light.
  32. //
  33. // * If you watch it for a bit, and then walk away, and then come back
  34. //   to it, you'll probably be able to "see" whether it's currently using
  35. //   the 'redder' or the 'bluer' temperature profile, even not counting
  36. //   the lowest 'indicator' pixel.
  37. //
  38. //
  39. // FastLED provides these pre-conigured incandescent color profiles:
  40. //     Candle, Tungsten40W, Tungsten100W, Halogen, CarbonArc,
  41. //     HighNoonSun, DirectSunlight, OvercastSky, ClearBlueSky,
  42. // FastLED provides these pre-configured gaseous-light color profiles:
  43. //     WarmFluorescent, StandardFluorescent, CoolWhiteFluorescent,
  44. //     FullSpectrumFluorescent, GrowLightFluorescent, BlackLightFluorescent,
  45. //     MercuryVapor, SodiumVapor, MetalHalide, HighPressureSodium,
  46. // FastLED also provides an "Uncorrected temperature" profile
  47. //    UncorrectedTemperature;

  48. #define TEMPERATURE_1 Tungsten100W
  49. #define TEMPERATURE_2 OvercastSky

  50. // How many seconds to show each temperature before switching
  51. #define DISPLAYTIME 20
  52. // How many seconds to show black between switches
  53. #define BLACKTIME   3

  54. void loop()
  55. {
  56.   // draw a generic, no-name rainbow
  57.   static uint8_t starthue = 0;
  58.   fill_rainbow( leds + 5, NUM_LEDS - 5, --starthue, 20);

  59.   // Choose which 'color temperature' profile to enable.
  60.   uint8_t secs = (millis() / 1000) % (DISPLAYTIME * 2);
  61.   if( secs < DISPLAYTIME) {
  62.     FastLED.setTemperature( TEMPERATURE_1 ); // first temperature
  63.     leds[0] = TEMPERATURE_1; // show indicator pixel
  64.   } else {
  65.     FastLED.setTemperature( TEMPERATURE_2 ); // second temperature
  66.     leds[0] = TEMPERATURE_2; // show indicator pixel
  67.   }

  68.   // Black out the LEDs for a few secnds between color changes
  69.   // to let the eyes and brains adjust
  70.   if( (secs % DISPLAYTIME) < BLACKTIME) {
  71.     memset8( leds, 0, NUM_LEDS * sizeof(CRGB));
  72.   }
  73.   
  74.   FastLED.show();
  75.   FastLED.delay(8);
  76. }

  77. void setup() {
  78.   delay( 3000 ); // power-up safety delay
  79.   // It's important to set the color correction for your LED strip here,
  80.   // so that colors can be more accurately rendered through the 'temperature' profiles
  81.   FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalSMD5050 );
  82.   FastLED.setBrightness( BRIGHTNESS );
  83. }
复制代码


 楼主| 发表于 2021-9-17 17:50 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  项目二十一:FastLED“100行代码”演示卷轴动画效果
  实验接线
  Module    UNO
  VCC —— 3.3V
  GND —— GND
  DI   ——  D6

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  3.   实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  4.   项目二十一:FastLED“100行代码”演示卷轴动画效果
  5.   实验接线
  6.   Module    UNO
  7.   VCC —— 3.3V
  8.   GND —— GND
  9.   DI  ——  D6
  10. */

  11. #include <FastLED.h>

  12. FASTLED_USING_NAMESPACE

  13. // FastLED "100-lines-of-code" demo reel, showing just a few
  14. // of the kinds of animation patterns you can quickly and easily
  15. // compose using FastLED.  
  16. //
  17. // This example also shows one easy way to define multiple
  18. // animations patterns and have them automatically rotate.
  19. //
  20. // -Mark Kriegsman, December 2014


  21. #define DATA_PIN    6
  22. //#define CLK_PIN   4
  23. #define LED_TYPE    WS2811
  24. #define COLOR_ORDER GRB
  25. #define NUM_LEDS    64
  26. CRGB leds[NUM_LEDS];

  27. #define BRIGHTNESS         26
  28. #define FRAMES_PER_SECOND  120

  29. void setup() {
  30.   delay(3000); // 3 second delay for recovery
  31.   
  32.   // tell FastLED about the LED strip configuration
  33.   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
  34.   //FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);

  35.   // set master brightness control
  36.   FastLED.setBrightness(BRIGHTNESS);
  37. }


  38. // List of patterns to cycle through.  Each is defined as a separate function below.
  39. typedef void (*SimplePatternList[])();
  40. SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm };

  41. uint8_t gCurrentPatternNumber = 0; // Index number of which pattern is current
  42. uint8_t gHue = 0; // rotating "base color" used by many of the patterns
  43.   
  44. void loop()
  45. {
  46.   // Call the current pattern function once, updating the 'leds' array
  47.   gPatterns[gCurrentPatternNumber]();

  48.   // send the 'leds' array out to the actual LED strip
  49.   FastLED.show();  
  50.   // insert a delay to keep the framerate modest
  51.   FastLED.delay(1000/FRAMES_PER_SECOND);

  52.   // do some periodic updates
  53.   EVERY_N_MILLISECONDS( 20 ) { gHue++; } // slowly cycle the "base color" through the rainbow
  54.   EVERY_N_SECONDS( 10 ) { nextPattern(); } // change patterns periodically
  55. }

  56. #define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))

  57. void nextPattern()
  58. {
  59.   // add one to the current pattern number, and wrap around at the end
  60.   gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE( gPatterns);
  61. }

  62. void rainbow()
  63. {
  64.   // FastLED's built-in rainbow generator
  65.   fill_rainbow( leds, NUM_LEDS, gHue, 7);
  66. }

  67. void rainbowWithGlitter()
  68. {
  69.   // built-in FastLED rainbow, plus some random sparkly glitter
  70.   rainbow();
  71.   addGlitter(80);
  72. }

  73. void addGlitter( fract8 chanceOfGlitter)
  74. {
  75.   if( random8() < chanceOfGlitter) {
  76.     leds[ random16(NUM_LEDS) ] += CRGB::White;
  77.   }
  78. }

  79. void confetti()
  80. {
  81.   // random colored speckles that blink in and fade smoothly
  82.   fadeToBlackBy( leds, NUM_LEDS, 10);
  83.   int pos = random16(NUM_LEDS);
  84.   leds[pos] += CHSV( gHue + random8(64), 200, 255);
  85. }

  86. void sinelon()
  87. {
  88.   // a colored dot sweeping back and forth, with fading trails
  89.   fadeToBlackBy( leds, NUM_LEDS, 20);
  90.   int pos = beatsin16( 13, 0, NUM_LEDS-1 );
  91.   leds[pos] += CHSV( gHue, 255, 192);
  92. }

  93. void bpm()
  94. {
  95.   // colored stripes pulsing at a defined Beats-Per-Minute (BPM)
  96.   uint8_t BeatsPerMinute = 62;
  97.   CRGBPalette16 palette = PartyColors_p;
  98.   uint8_t beat = beatsin8( BeatsPerMinute, 64, 255);
  99.   for( int i = 0; i < NUM_LEDS; i++) { //9948
  100.     leds[i] = ColorFromPalette(palette, gHue+(i*2), beat-gHue+(i*10));
  101.   }
  102. }

  103. void juggle() {
  104.   // eight colored dots, weaving in and out of sync with each other
  105.   fadeToBlackBy( leds, NUM_LEDS, 20);
  106.   uint8_t dothue = 0;
  107.   for( int i = 0; i < 8; i++) {
  108.     leds[beatsin16( i+7, 0, NUM_LEDS-1 )] |= CHSV(dothue, 200, 255);
  109.     dothue += 32;
  110.   }
  111. }
复制代码


 楼主| 发表于 2021-9-17 17:56 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  项目二十二:随机60帧火焰花
  实验接线
  Module    UNO
  VCC —— 3.3V
  GND —— GND
  DI  ——  D6

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  3.   实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  4.   项目二十二:随机60帧火焰花
  5.   实验接线
  6.   Module    UNO
  7.   VCC —— 3.3V
  8.   GND —— GND
  9.   DI  ——  D6
  10. */

  11. #include <FastLED.h>

  12. #define LED_PIN     6
  13. #define COLOR_ORDER GRB
  14. #define CHIPSET     WS2811
  15. #define NUM_LEDS    16

  16. #define BRIGHTNESS  22
  17. #define FRAMES_PER_SECOND 60

  18. bool gReverseDirection = false;

  19. CRGB leds[NUM_LEDS];

  20. void setup() {
  21.   delay(3000); // sanity delay
  22.   FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  23.   FastLED.setBrightness( BRIGHTNESS );
  24. }

  25. void loop()
  26. {
  27.   // Add entropy to random number generator; we use a lot of it.
  28.   // random16_add_entropy( random());

  29.   Fire2012(); // run simulation frame

  30.   FastLED.show(); // display this frame
  31.   FastLED.delay(1000 / FRAMES_PER_SECOND);
  32. }


  33. // Fire2012 by Mark Kriegsman, July 2012
  34. // as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY
  35. ////
  36. // This basic one-dimensional 'fire' simulation works roughly as follows:
  37. // There's a underlying array of 'heat' cells, that model the temperature
  38. // at each point along the line.  Every cycle through the simulation,
  39. // four steps are performed:
  40. //  1) All cells cool down a little bit, losing heat to the air
  41. //  2) The heat from each cell drifts 'up' and diffuses a little
  42. //  3) Sometimes randomly new 'sparks' of heat are added at the bottom
  43. //  4) The heat from each cell is rendered as a color into the leds array
  44. //     The heat-to-color mapping uses a black-body radiation approximation.
  45. //
  46. // Temperature is in arbitrary units from 0 (cold black) to 255 (white hot).
  47. //
  48. // This simulation scales it self a bit depending on NUM_LEDS; it should look
  49. // "OK" on anywhere from 20 to 100 LEDs without too much tweaking.
  50. //
  51. // I recommend running this simulation at anywhere from 30-100 frames per second,
  52. // meaning an interframe delay of about 10-35 milliseconds.
  53. //
  54. // Looks best on a high-density LED setup (60+ pixels/meter).
  55. //
  56. //
  57. // There are two main parameters you can play with to control the look and
  58. // feel of your fire: COOLING (used in step 1 above), and SPARKING (used
  59. // in step 3 above).
  60. //
  61. // COOLING: How much does the air cool as it rises?
  62. // Less cooling = taller flames.  More cooling = shorter flames.
  63. // Default 50, suggested range 20-100
  64. #define COOLING  55

  65. // SPARKING: What chance (out of 255) is there that a new spark will be lit?
  66. // Higher chance = more roaring fire.  Lower chance = more flickery fire.
  67. // Default 120, suggested range 50-200.
  68. #define SPARKING 120


  69. void Fire2012()
  70. {
  71.   // Array of temperature readings at each simulation cell
  72.   static uint8_t heat[NUM_LEDS];

  73.   // Step 1.  Cool down every cell a little
  74.   for ( int i = 0; i < NUM_LEDS; i++) {
  75.     heat[i] = qsub8( heat[i],  random8(0, ((COOLING * 10) / NUM_LEDS) + 2));
  76.   }

  77.   // Step 2.  Heat from each cell drifts 'up' and diffuses a little
  78.   for ( int k = NUM_LEDS - 1; k >= 2; k--) {
  79.     heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
  80.   }

  81.   // Step 3.  Randomly ignite new 'sparks' of heat near the bottom
  82.   if ( random8() < SPARKING ) {
  83.     int y = random8(7);
  84.     heat[y] = qadd8( heat[y], random8(160, 255) );
  85.   }

  86.   // Step 4.  Map from heat cells to LED colors
  87.   for ( int j = 0; j < NUM_LEDS; j++) {
  88.     CRGB color = HeatColor( heat[j]);
  89.     int pixelnumber;
  90.     if ( gReverseDirection ) {
  91.       pixelnumber = (NUM_LEDS - 1) - j;
  92.     } else {
  93.       pixelnumber = j;
  94.     }
  95.     leds[pixelnumber] = color;
  96.   }
  97. }
复制代码


 楼主| 发表于 2021-9-17 18:17 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  项目二十三:带有可编程调色板的 Fire2012 火灾模拟
  实验接线
  Module    UNO
  VCC —— 3.3V
  GND —— GND
  DI  ——  D6

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  3.   实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  4.   项目二十三:带有可编程调色板的 Fire2012 火灾模拟
  5.   实验接线
  6.   Module    UNO
  7.   VCC —— 3.3V
  8.   GND —— GND
  9.   DI  ——  D6
  10. */

  11. #include <FastLED.h>

  12. #define LED_PIN     6
  13. #define COLOR_ORDER GRB
  14. #define CHIPSET     WS2811
  15. #define NUM_LEDS    16

  16. #define BRIGHTNESS  22
  17. #define FRAMES_PER_SECOND 60

  18. bool gReverseDirection = false;

  19. CRGB leds[NUM_LEDS];

  20. // Fire2012 with programmable Color Palette
  21. //
  22. // This code is the same fire simulation as the original "Fire2012",
  23. // but each heat cell's temperature is translated to color through a FastLED
  24. // programmable color palette, instead of through the "HeatColor(...)" function.
  25. //
  26. // Four different static color palettes are provided here, plus one dynamic one.
  27. //
  28. // The three static ones are:
  29. //   1. the FastLED built-in HeatColors_p -- this is the default, and it looks
  30. //      pretty much exactly like the original Fire2012.
  31. //
  32. //  To use any of the other palettes below, just "uncomment" the corresponding code.
  33. //
  34. //   2. a gradient from black to red to yellow to white, which is
  35. //      visually similar to the HeatColors_p, and helps to illustrate
  36. //      what the 'heat colors' palette is actually doing,
  37. //   3. a similar gradient, but in blue colors rather than red ones,
  38. //      i.e. from black to blue to aqua to white, which results in
  39. //      an "icy blue" fire effect,
  40. //   4. a simplified three-step gradient, from black to red to white, just to show
  41. //      that these gradients need not have four components; two or
  42. //      three are possible, too, even if they don't look quite as nice for fire.
  43. //
  44. // The dynamic palette shows how you can change the basic 'hue' of the
  45. // color palette every time through the loop, producing "rainbow fire".

  46. CRGBPalette16 gPal;

  47. void setup() {
  48.   delay(3000); // sanity delay
  49.   FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  50.   FastLED.setBrightness( BRIGHTNESS );

  51.   // This first palette is the basic 'black body radiation' colors,
  52.   // which run from black to red to bright yellow to white.
  53.   gPal = HeatColors_p;
  54.   
  55.   // These are other ways to set up the color palette for the 'fire'.
  56.   // First, a gradient from black to red to yellow to white -- similar to HeatColors_p
  57.   //   gPal = CRGBPalette16( CRGB::Black, CRGB::Red, CRGB::Yellow, CRGB::White);
  58.   
  59.   // Second, this palette is like the heat colors, but blue/aqua instead of red/yellow
  60.   //   gPal = CRGBPalette16( CRGB::Black, CRGB::Blue, CRGB::Aqua,  CRGB::White);
  61.   
  62.   // Third, here's a simpler, three-step gradient, from black to red to white
  63.   //   gPal = CRGBPalette16( CRGB::Black, CRGB::Red, CRGB::White);

  64. }

  65. void loop()
  66. {
  67.   // Add entropy to random number generator; we use a lot of it.
  68.   random16_add_entropy( random());

  69.   // Fourth, the most sophisticated: this one sets up a new palette every
  70.   // time through the loop, based on a hue that changes every time.
  71.   // The palette is a gradient from black, to a dark color based on the hue,
  72.   // to a light color based on the hue, to white.
  73.   //
  74.   //   static uint8_t hue = 0;
  75.   //   hue++;
  76.   //   CRGB darkcolor  = CHSV(hue,255,192); // pure hue, three-quarters brightness
  77.   //   CRGB lightcolor = CHSV(hue,128,255); // half 'whitened', full brightness
  78.   //   gPal = CRGBPalette16( CRGB::Black, darkcolor, lightcolor, CRGB::White);


  79.   Fire2012WithPalette(); // run simulation frame, using palette colors
  80.   
  81.   FastLED.show(); // display this frame
  82.   FastLED.delay(1000 / FRAMES_PER_SECOND);
  83. }


  84. // Fire2012 by Mark Kriegsman, July 2012
  85. // as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY
  86. ////
  87. // This basic one-dimensional 'fire' simulation works roughly as follows:
  88. // There's a underlying array of 'heat' cells, that model the temperature
  89. // at each point along the line.  Every cycle through the simulation,
  90. // four steps are performed:
  91. //  1) All cells cool down a little bit, losing heat to the air
  92. //  2) The heat from each cell drifts 'up' and diffuses a little
  93. //  3) Sometimes randomly new 'sparks' of heat are added at the bottom
  94. //  4) The heat from each cell is rendered as a color into the leds array
  95. //     The heat-to-color mapping uses a black-body radiation approximation.
  96. //
  97. // Temperature is in arbitrary units from 0 (cold black) to 255 (white hot).
  98. //
  99. // This simulation scales it self a bit depending on NUM_LEDS; it should look
  100. // "OK" on anywhere from 20 to 100 LEDs without too much tweaking.
  101. //
  102. // I recommend running this simulation at anywhere from 30-100 frames per second,
  103. // meaning an interframe delay of about 10-35 milliseconds.
  104. //
  105. // Looks best on a high-density LED setup (60+ pixels/meter).
  106. //
  107. //
  108. // There are two main parameters you can play with to control the look and
  109. // feel of your fire: COOLING (used in step 1 above), and SPARKING (used
  110. // in step 3 above).
  111. //
  112. // COOLING: How much does the air cool as it rises?
  113. // Less cooling = taller flames.  More cooling = shorter flames.
  114. // Default 55, suggested range 20-100
  115. #define COOLING  55

  116. // SPARKING: What chance (out of 255) is there that a new spark will be lit?
  117. // Higher chance = more roaring fire.  Lower chance = more flickery fire.
  118. // Default 120, suggested range 50-200.
  119. #define SPARKING 120


  120. void Fire2012WithPalette()
  121. {
  122. // Array of temperature readings at each simulation cell
  123.   static uint8_t heat[NUM_LEDS];

  124.   // Step 1.  Cool down every cell a little
  125.     for( int i = 0; i < NUM_LEDS; i++) {
  126.       heat[i] = qsub8( heat[i],  random8(0, ((COOLING * 10) / NUM_LEDS) + 2));
  127.     }
  128.   
  129.     // Step 2.  Heat from each cell drifts 'up' and diffuses a little
  130.     for( int k= NUM_LEDS - 1; k >= 2; k--) {
  131.       heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
  132.     }
  133.    
  134.     // Step 3.  Randomly ignite new 'sparks' of heat near the bottom
  135.     if( random8() < SPARKING ) {
  136.       int y = random8(7);
  137.       heat[y] = qadd8( heat[y], random8(160,255) );
  138.     }

  139.     // Step 4.  Map from heat cells to LED colors
  140.     for( int j = 0; j < NUM_LEDS; j++) {
  141.       // Scale the heat value from 0-255 down to 0-240
  142.       // for best results with color palettes.
  143.       uint8_t colorindex = scale8( heat[j], 240);
  144.       CRGB color = ColorFromPalette( gPal, colorindex);
  145.       int pixelnumber;
  146.       if( gReverseDirection ) {
  147.         pixelnumber = (NUM_LEDS-1) - j;
  148.       } else {
  149.         pixelnumber = j;
  150.       }
  151.       leds[pixelnumber] = color;
  152.     }
  153. }
复制代码


 楼主| 发表于 2021-9-17 19:03 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  项目二十四:骄傲2015动画,不断变化的彩虹
  实验接线
  Module    UNO
  VCC —— 3.3V
  GND —— GND
  DI  ——  D6

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  3.   实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  4.   项目二十四:骄傲2015动画,不断变化的彩虹
  5.   实验接线
  6.   Module    UNO
  7.   VCC —— 3.3V
  8.   GND —— GND
  9.   DI  ——  D6
  10. */

  11. #include "FastLED.h"

  12. // Pride2015
  13. // Animated, ever-changing rainbows.
  14. // by Mark Kriegsman

  15. #if FASTLED_VERSION < 3001000
  16. #error "Requires FastLED 3.1 or later; check github for latest code."
  17. #endif

  18. #define DATA_PIN    6
  19. //#define CLK_PIN   4
  20. #define LED_TYPE    WS2811
  21. #define COLOR_ORDER GRB
  22. #define NUM_LEDS    16
  23. #define BRIGHTNESS  25

  24. CRGB leds[NUM_LEDS];


  25. void setup() {
  26.   delay(3000); // 3 second delay for recovery
  27.   
  28.   // tell FastLED about the LED strip configuration
  29.   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
  30.     .setCorrection(TypicalLEDStrip)
  31.     .setDither(BRIGHTNESS < 255);

  32.   // set master brightness control
  33.   FastLED.setBrightness(BRIGHTNESS);
  34. }


  35. void loop()
  36. {
  37.   pride();
  38.   FastLED.show();  
  39. }


  40. // This function draws rainbows with an ever-changing,
  41. // widely-varying set of parameters.
  42. void pride()
  43. {
  44.   static uint16_t sPseudotime = 0;
  45.   static uint16_t sLastMillis = 0;
  46.   static uint16_t sHue16 = 0;

  47.   uint8_t sat8 = beatsin88( 87, 220, 250);
  48.   uint8_t brightdepth = beatsin88( 341, 96, 224);
  49.   uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
  50.   uint8_t msmultiplier = beatsin88(147, 23, 60);

  51.   uint16_t hue16 = sHue16;//gHue * 256;
  52.   uint16_t hueinc16 = beatsin88(113, 1, 3000);
  53.   
  54.   uint16_t ms = millis();
  55.   uint16_t deltams = ms - sLastMillis ;
  56.   sLastMillis  = ms;
  57.   sPseudotime += deltams * msmultiplier;
  58.   sHue16 += deltams * beatsin88( 400, 5,9);
  59.   uint16_t brightnesstheta16 = sPseudotime;
  60.   
  61.   for( uint16_t i = 0 ; i < NUM_LEDS; i++) {
  62.     hue16 += hueinc16;
  63.     uint8_t hue8 = hue16 / 256;

  64.     brightnesstheta16  += brightnessthetainc16;
  65.     uint16_t b16 = sin16( brightnesstheta16  ) + 32768;

  66.     uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
  67.     uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
  68.     bri8 += (255 - brightdepth);
  69.    
  70.     CRGB newcolor = CHSV( hue8, sat8, bri8);
  71.    
  72.     uint16_t pixelnumber = i;
  73.     pixelnumber = (NUM_LEDS-1) - pixelnumber;
  74.    
  75.     nblend( leds[pixelnumber], newcolor, 64);
  76.   }
  77. }
复制代码



 楼主| 发表于 2021-9-17 20:27 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  项目二十五:TwinkleFOX:淡入淡出的闪烁“假日”灯
  实验接线
  Module    UNO
  VCC —— 3.3V
  GND —— GND
  DI  ——  D6

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  3.   实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  4.   项目二十五:TwinkleFOX:淡入淡出的闪烁“假日”灯
  5.   实验接线
  6.   Module    UNO
  7.   VCC —— 3.3V
  8.   GND —— GND
  9.   DI  ——  D6
  10. */

  11. #include "FastLED.h"

  12. #define NUM_LEDS      16
  13. #define LED_TYPE   WS2811
  14. #define COLOR_ORDER   GRB
  15. #define DATA_PIN        6
  16. //#define CLK_PIN       4
  17. #define VOLTS          12
  18. #define MAX_MA       4000

  19. //  TwinkleFOX: Twinkling 'holiday' lights that fade in and out.
  20. //  Colors are chosen from a palette; a few palettes are provided.
  21. //
  22. //  This December 2015 implementation improves on the December 2014 version
  23. //  in several ways:
  24. //  - smoother fading, compatible with any colors and any palettes
  25. //  - easier control of twinkle speed and twinkle density
  26. //  - supports an optional 'background color'
  27. //  - takes even less RAM: zero RAM overhead per pixel
  28. //  - illustrates a couple of interesting techniques (uh oh...)
  29. //
  30. //  The idea behind this (new) implementation is that there's one
  31. //  basic, repeating pattern that each pixel follows like a waveform:
  32. //  The brightness rises from 0..255 and then falls back down to 0.
  33. //  The brightness at any given point in time can be determined as
  34. //  as a function of time, for example:
  35. //    brightness = sine( time ); // a sine wave of brightness over time
  36. //
  37. //  So the way this implementation works is that every pixel follows
  38. //  the exact same wave function over time.  In this particular case,
  39. //  I chose a sawtooth triangle wave (triwave8) rather than a sine wave,
  40. //  but the idea is the same: brightness = triwave8( time ).
  41. //
  42. //  Of course, if all the pixels used the exact same wave form, and
  43. //  if they all used the exact same 'clock' for their 'time base', all
  44. //  the pixels would brighten and dim at once -- which does not look
  45. //  like twinkling at all.
  46. //
  47. //  So to achieve random-looking twinkling, each pixel is given a
  48. //  slightly different 'clock' signal.  Some of the clocks run faster,
  49. //  some run slower, and each 'clock' also has a random offset from zero.
  50. //  The net result is that the 'clocks' for all the pixels are always out
  51. //  of sync from each other, producing a nice random distribution
  52. //  of twinkles.
  53. //
  54. //  The 'clock speed adjustment' and 'time offset' for each pixel
  55. //  are generated randomly.  One (normal) approach to implementing that
  56. //  would be to randomly generate the clock parameters for each pixel
  57. //  at startup, and store them in some arrays.  However, that consumes
  58. //  a great deal of precious RAM, and it turns out to be totally
  59. //  unnessary!  If the random number generate is 'seeded' with the
  60. //  same starting value every time, it will generate the same sequence
  61. //  of values every time.  So the clock adjustment parameters for each
  62. //  pixel are 'stored' in a pseudo-random number generator!  The PRNG
  63. //  is reset, and then the first numbers out of it are the clock
  64. //  adjustment parameters for the first pixel, the second numbers out
  65. //  of it are the parameters for the second pixel, and so on.
  66. //  In this way, we can 'store' a stable sequence of thousands of
  67. //  random clock adjustment parameters in literally two bytes of RAM.
  68. //
  69. //  There's a little bit of fixed-point math involved in applying the
  70. //  clock speed adjustments, which are expressed in eighths.  Each pixel's
  71. //  clock speed ranges from 8/8ths of the system clock (i.e. 1x) to
  72. //  23/8ths of the system clock (i.e. nearly 3x).
  73. //
  74. //  On a basic Arduino Uno or Leonardo, this code can twinkle 300+ pixels
  75. //  smoothly at over 50 updates per seond.
  76. //
  77. //  -Mark Kriegsman, December 2015

  78. CRGBArray<NUM_LEDS> leds;

  79. // Overall twinkle speed.
  80. // 0 (VERY slow) to 8 (VERY fast).
  81. // 4, 5, and 6 are recommended, default is 4.
  82. #define TWINKLE_SPEED 4

  83. // Overall twinkle density.
  84. // 0 (NONE lit) to 8 (ALL lit at once).
  85. // Default is 5.
  86. #define TWINKLE_DENSITY 5

  87. // How often to change color palettes.
  88. #define SECONDS_PER_PALETTE  30
  89. // Also: toward the bottom of the file is an array
  90. // called "ActivePaletteList" which controls which color
  91. // palettes are used; you can add or remove color palettes
  92. // from there freely.

  93. // Background color for 'unlit' pixels
  94. // Can be set to CRGB::Black if desired.
  95. CRGB gBackgroundColor = CRGB::Black;
  96. // Example of dim incandescent fairy light background color
  97. // CRGB gBackgroundColor = CRGB(CRGB::FairyLight).nscale8_video(16);

  98. // If AUTO_SELECT_BACKGROUND_COLOR is set to 1,
  99. // then for any palette where the first two entries
  100. // are the same, a dimmed version of that color will
  101. // automatically be used as the background color.
  102. #define AUTO_SELECT_BACKGROUND_COLOR 0

  103. // If COOL_LIKE_INCANDESCENT is set to 1, colors will
  104. // fade out slighted 'reddened', similar to how
  105. // incandescent bulbs change color as they get dim down.
  106. #define COOL_LIKE_INCANDESCENT 1


  107. CRGBPalette16 gCurrentPalette;
  108. CRGBPalette16 gTargetPalette;

  109. void setup() {
  110.   delay( 3000 ); //safety startup delay
  111.   FastLED.setMaxPowerInVoltsAndMilliamps( VOLTS, MAX_MA);
  112.   FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS)
  113.   .setCorrection(TypicalLEDStrip);
  114.   FastLED.setBrightness(23);
  115.   chooseNextColorPalette(gTargetPalette);
  116. }


  117. void loop()
  118. {
  119.   EVERY_N_SECONDS( SECONDS_PER_PALETTE ) {
  120.     chooseNextColorPalette( gTargetPalette );
  121.   }

  122.   EVERY_N_MILLISECONDS( 10 ) {
  123.     nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 12);
  124.   }

  125.   drawTwinkles( leds);

  126.   FastLED.show();
  127. }


  128. //  This function loops over each pixel, calculates the
  129. //  adjusted 'clock' that this pixel should use, and calls
  130. //  "CalculateOneTwinkle" on each pixel.  It then displays
  131. //  either the twinkle color of the background color,
  132. //  whichever is brighter.
  133. void drawTwinkles( CRGBSet& L)
  134. {
  135.   // "PRNG16" is the pseudorandom number generator
  136.   // It MUST be reset to the same starting value each time
  137.   // this function is called, so that the sequence of 'random'
  138.   // numbers that it generates is (paradoxically) stable.
  139.   uint16_t PRNG16 = 11337;

  140.   uint32_t clock32 = millis();

  141.   // Set up the background color, "bg".
  142.   // if AUTO_SELECT_BACKGROUND_COLOR == 1, and the first two colors of
  143.   // the current palette are identical, then a deeply faded version of
  144.   // that color is used for the background color
  145.   CRGB bg;
  146.   if ( (AUTO_SELECT_BACKGROUND_COLOR == 1) &&
  147.        (gCurrentPalette[0] == gCurrentPalette[1] )) {
  148.     bg = gCurrentPalette[0];
  149.     uint8_t bglight = bg.getAverageLight();
  150.     if ( bglight > 64) {
  151.       bg.nscale8_video( 16); // very bright, so scale to 1/16th
  152.     } else if ( bglight > 16) {
  153.       bg.nscale8_video( 64); // not that bright, so scale to 1/4th
  154.     } else {
  155.       bg.nscale8_video( 86); // dim, scale to 1/3rd.
  156.     }
  157.   } else {
  158.     bg = gBackgroundColor; // just use the explicitly defined background color
  159.   }

  160.   uint8_t backgroundBrightness = bg.getAverageLight();

  161.   for ( CRGB& pixel : L) {
  162.     PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
  163.     uint16_t myclockoffset16 = PRNG16; // use that number as clock offset
  164.     PRNG16 = (uint16_t)(PRNG16 * 2053) + 1384; // next 'random' number
  165.     // use that number as clock speed adjustment factor (in 8ths, from 8/8ths to 23/8ths)
  166.     uint8_t myspeedmultiplierQ5_3 =  ((((PRNG16 & 0xFF) >> 4) + (PRNG16 & 0x0F)) & 0x0F) + 0x08;
  167.     uint32_t myclock30 = (uint32_t)((clock32 * myspeedmultiplierQ5_3) >> 3) + myclockoffset16;
  168.     uint8_t  myunique8 = PRNG16 >> 8; // get 'salt' value for this pixel

  169.     // We now have the adjusted 'clock' for this pixel, now we call
  170.     // the function that computes what color the pixel should be based
  171.     // on the "brightness = f( time )" idea.
  172.     CRGB c = computeOneTwinkle( myclock30, myunique8);

  173.     uint8_t cbright = c.getAverageLight();
  174.     int16_t deltabright = cbright - backgroundBrightness;
  175.     if ( deltabright >= 32 || (!bg)) {
  176.       // If the new pixel is significantly brighter than the background color,
  177.       // use the new color.
  178.       pixel = c;
  179.     } else if ( deltabright > 0 ) {
  180.       // If the new pixel is just slightly brighter than the background color,
  181.       // mix a blend of the new color and the background color
  182.       pixel = blend( bg, c, deltabright * 8);
  183.     } else {
  184.       // if the new pixel is not at all brighter than the background color,
  185.       // just use the background color.
  186.       pixel = bg;
  187.     }
  188.   }
  189. }


  190. //  This function takes a time in pseudo-milliseconds,
  191. //  figures out brightness = f( time ), and also hue = f( time )
  192. //  The 'low digits' of the millisecond time are used as
  193. //  input to the brightness wave function.
  194. //  The 'high digits' are used to select a color, so that the color
  195. //  does not change over the course of the fade-in, fade-out
  196. //  of one cycle of the brightness wave function.
  197. //  The 'high digits' are also used to determine whether this pixel
  198. //  should light at all during this cycle, based on the TWINKLE_DENSITY.
  199. CRGB computeOneTwinkle( uint32_t ms, uint8_t salt)
  200. {
  201.   uint16_t ticks = ms >> (8 - TWINKLE_SPEED);
  202.   uint8_t fastcycle8 = ticks;
  203.   uint16_t slowcycle16 = (ticks >> 8) + salt;
  204.   slowcycle16 += sin8( slowcycle16);
  205.   slowcycle16 =  (slowcycle16 * 2053) + 1384;
  206.   uint8_t slowcycle8 = (slowcycle16 & 0xFF) + (slowcycle16 >> 8);

  207.   uint8_t bright = 0;
  208.   if ( ((slowcycle8 & 0x0E) / 2) < TWINKLE_DENSITY) {
  209.     bright = attackDecayWave8( fastcycle8);
  210.   }

  211.   uint8_t hue = slowcycle8 - salt;
  212.   CRGB c;
  213.   if ( bright > 0) {
  214.     c = ColorFromPalette( gCurrentPalette, hue, bright, NOBLEND);
  215.     if ( COOL_LIKE_INCANDESCENT == 1 ) {
  216.       coolLikeIncandescent( c, fastcycle8);
  217.     }
  218.   } else {
  219.     c = CRGB::Black;
  220.   }
  221.   return c;
  222. }


  223. // This function is like 'triwave8', which produces a
  224. // symmetrical up-and-down triangle sawtooth waveform, except that this
  225. // function produces a triangle wave with a faster attack and a slower decay:
  226. //
  227. //     / \
  228. //    /     \
  229. //   /         \
  230. //  /             \
  231. //

  232. uint8_t attackDecayWave8( uint8_t i)
  233. {
  234.   if ( i < 86) {
  235.     return i * 3;
  236.   } else {
  237.     i -= 86;
  238.     return 255 - (i + (i / 2));
  239.   }
  240. }

  241. // This function takes a pixel, and if its in the 'fading down'
  242. // part of the cycle, it adjusts the color a little bit like the
  243. // way that incandescent bulbs fade toward 'red' as they dim.
  244. void coolLikeIncandescent( CRGB& c, uint8_t phase)
  245. {
  246.   if ( phase < 128) return;

  247.   uint8_t cooling = (phase - 128) >> 4;
  248.   c.g = qsub8( c.g, cooling);
  249.   c.b = qsub8( c.b, cooling * 2);
  250. }

  251. // A mostly red palette with green accents and white trim.
  252. // "CRGB::Gray" is used as white to keep the brightness more uniform.
  253. const TProgmemRGBPalette16 RedGreenWhite_p FL_PROGMEM =
  254. { CRGB::Red, CRGB::Red, CRGB::Red, CRGB::Red,
  255.   CRGB::Red, CRGB::Red, CRGB::Red, CRGB::Red,
  256.   CRGB::Red, CRGB::Red, CRGB::Gray, CRGB::Gray,
  257.   CRGB::Green, CRGB::Green, CRGB::Green, CRGB::Green
  258. };

  259. // A mostly (dark) green palette with red berries.
  260. #define Holly_Green 0x00580c
  261. #define Holly_Red   0xB00402
  262. const TProgmemRGBPalette16 Holly_p FL_PROGMEM =
  263. { Holly_Green, Holly_Green, Holly_Green, Holly_Green,
  264.   Holly_Green, Holly_Green, Holly_Green, Holly_Green,
  265.   Holly_Green, Holly_Green, Holly_Green, Holly_Green,
  266.   Holly_Green, Holly_Green, Holly_Green, Holly_Red
  267. };

  268. // A red and white striped palette
  269. // "CRGB::Gray" is used as white to keep the brightness more uniform.
  270. const TProgmemRGBPalette16 RedWhite_p FL_PROGMEM =
  271. { CRGB::Red,  CRGB::Red,  CRGB::Red,  CRGB::Red,
  272.   CRGB::Gray, CRGB::Gray, CRGB::Gray, CRGB::Gray,
  273.   CRGB::Red,  CRGB::Red,  CRGB::Red,  CRGB::Red,
  274.   CRGB::Gray, CRGB::Gray, CRGB::Gray, CRGB::Gray
  275. };

  276. // A mostly blue palette with white accents.
  277. // "CRGB::Gray" is used as white to keep the brightness more uniform.
  278. const TProgmemRGBPalette16 BlueWhite_p FL_PROGMEM =
  279. { CRGB::Blue, CRGB::Blue, CRGB::Blue, CRGB::Blue,
  280.   CRGB::Blue, CRGB::Blue, CRGB::Blue, CRGB::Blue,
  281.   CRGB::Blue, CRGB::Blue, CRGB::Blue, CRGB::Blue,
  282.   CRGB::Blue, CRGB::Gray, CRGB::Gray, CRGB::Gray
  283. };

  284. // A pure "fairy light" palette with some brightness variations
  285. #define HALFFAIRY ((CRGB::FairyLight & 0xFEFEFE) / 2)
  286. #define QUARTERFAIRY ((CRGB::FairyLight & 0xFCFCFC) / 4)
  287. const TProgmemRGBPalette16 FairyLight_p FL_PROGMEM =
  288. { CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight,
  289.   HALFFAIRY,        HALFFAIRY,        CRGB::FairyLight, CRGB::FairyLight,
  290.   QUARTERFAIRY,     QUARTERFAIRY,     CRGB::FairyLight, CRGB::FairyLight,
  291.   CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight
  292. };

  293. // A palette of soft snowflakes with the occasional bright one
  294. const TProgmemRGBPalette16 Snow_p FL_PROGMEM =
  295. { 0x304048, 0x304048, 0x304048, 0x304048,
  296.   0x304048, 0x304048, 0x304048, 0x304048,
  297.   0x304048, 0x304048, 0x304048, 0x304048,
  298.   0x304048, 0x304048, 0x304048, 0xE0F0FF
  299. };

  300. // A palette reminiscent of large 'old-school' C9-size tree lights
  301. // in the five classic colors: red, orange, green, blue, and white.
  302. #define C9_Red    0xB80400
  303. #define C9_Orange 0x902C02
  304. #define C9_Green  0x046002
  305. #define C9_Blue   0x070758
  306. #define C9_White  0x606820
  307. const TProgmemRGBPalette16 RetroC9_p FL_PROGMEM =
  308. { C9_Red,    C9_Orange, C9_Red,    C9_Orange,
  309.   C9_Orange, C9_Red,    C9_Orange, C9_Red,
  310.   C9_Green,  C9_Green,  C9_Green,  C9_Green,
  311.   C9_Blue,   C9_Blue,   C9_Blue,
  312.   C9_White
  313. };

  314. // A cold, icy pale blue palette
  315. #define Ice_Blue1 0x0C1040
  316. #define Ice_Blue2 0x182080
  317. #define Ice_Blue3 0x5080C0
  318. const TProgmemRGBPalette16 Ice_p FL_PROGMEM =
  319. {
  320.   Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
  321.   Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
  322.   Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
  323.   Ice_Blue2, Ice_Blue2, Ice_Blue2, Ice_Blue3
  324. };


  325. // Add or remove palette names from this list to control which color
  326. // palettes are used, and in what order.
  327. const TProgmemRGBPalette16* ActivePaletteList[] = {
  328.   &RetroC9_p,
  329.   &BlueWhite_p,
  330.   &RainbowColors_p,
  331.   &FairyLight_p,
  332.   &RedGreenWhite_p,
  333.   &PartyColors_p,
  334.   &RedWhite_p,
  335.   &Snow_p,
  336.   &Holly_p,
  337.   &Ice_p
  338. };


  339. // Advance to the next color palette in the list (above).
  340. void chooseNextColorPalette( CRGBPalette16& pal)
  341. {
  342.   const uint8_t numberOfPalettes = sizeof(ActivePaletteList) / sizeof(ActivePaletteList[0]);
  343.   static uint8_t whichPalette = -1;
  344.   whichPalette = addmod8( whichPalette, 1, numberOfPalettes);

  345.   pal = *(ActivePaletteList[whichPalette]);
  346. }
复制代码


 楼主| 发表于 2021-9-17 20:30 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  项目二十六:二维 XY 像素矩阵闪烁灯
  实验接线
  Module    UNO
  VCC —— 3.3V
  GND —— GND
  DI  ——  D6

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料+代码+图形+仿真)
  3.   实验八十九: WS2812B-4*4位 RGB LED 全彩驱动16位彩灯开发板
  4.   项目二十六:二维 XY 像素矩阵闪烁灯
  5.   实验接线
  6.   Module    UNO
  7.   VCC —— 3.3V
  8.   GND —— GND
  9.   DI  ——  D6
  10. */

  11. #include <FastLED.h>

  12. #define LED_PIN  6

  13. #define COLOR_ORDER GRB
  14. #define CHIPSET     WS2811

  15. #define BRIGHTNESS 26

  16. // Helper functions for an two-dimensional XY matrix of pixels.
  17. // Simple 2-D demo code is included as well.
  18. //
  19. //     XY(x,y) takes x and y coordinates and returns an LED index number,
  20. //             for use like this:  leds[ XY(x,y) ] == CRGB::Red;
  21. //             No error checking is performed on the ranges of x and y.
  22. //
  23. //     XYsafe(x,y) takes x and y coordinates and returns an LED index number,
  24. //             for use like this:  leds[ XYsafe(x,y) ] == CRGB::Red;
  25. //             Error checking IS performed on the ranges of x and y, and an
  26. //             index of "-1" is returned.  Special instructions below
  27. //             explain how to use this without having to do your own error
  28. //             checking every time you use this function.  
  29. //             This is a slightly more advanced technique, and
  30. //             it REQUIRES SPECIAL ADDITIONAL setup, described below.


  31. // Params for width and height
  32. const uint8_t kMatrixWidth = 16;
  33. const uint8_t kMatrixHeight = 16;

  34. // Param for different pixel layouts
  35. const bool    kMatrixSerpentineLayout = true;
  36. const bool    kMatrixVertical = false;

  37. // Set 'kMatrixSerpentineLayout' to false if your pixels are
  38. // laid out all running the same way, like this:
  39. //
  40. //     0 >  1 >  2 >  3 >  4
  41. //                         |
  42. //     .----<----<----<----'
  43. //     |
  44. //     5 >  6 >  7 >  8 >  9
  45. //                         |
  46. //     .----<----<----<----'
  47. //     |
  48. //    10 > 11 > 12 > 13 > 14
  49. //                         |
  50. //     .----<----<----<----'
  51. //     |
  52. //    15 > 16 > 17 > 18 > 19
  53. //
  54. // Set 'kMatrixSerpentineLayout' to true if your pixels are
  55. // laid out back-and-forth, like this:
  56. //
  57. //     0 >  1 >  2 >  3 >  4
  58. //                         |
  59. //                         |
  60. //     9 <  8 <  7 <  6 <  5
  61. //     |
  62. //     |
  63. //    10 > 11 > 12 > 13 > 14
  64. //                        |
  65. //                        |
  66. //    19 < 18 < 17 < 16 < 15
  67. //
  68. // Bonus vocabulary word: anything that goes one way
  69. // in one row, and then backwards in the next row, and so on
  70. // is call "boustrophedon", meaning "as the ox plows."


  71. // This function will return the right 'led index number' for
  72. // a given set of X and Y coordinates on your matrix.  
  73. // IT DOES NOT CHECK THE COORDINATE BOUNDARIES.  
  74. // That's up to you.  Don't pass it bogus values.
  75. //
  76. // Use the "XY" function like this:
  77. //
  78. //    for( uint8_t x = 0; x < kMatrixWidth; x++) {
  79. //      for( uint8_t y = 0; y < kMatrixHeight; y++) {
  80. //      
  81. //        // Here's the x, y to 'led index' in action:
  82. //        leds[ XY( x, y) ] = CHSV( random8(), 255, 255);
  83. //      
  84. //      }
  85. //    }
  86. //
  87. //
  88. uint16_t XY( uint8_t x, uint8_t y)
  89. {
  90.   uint16_t i;
  91.   
  92.   if( kMatrixSerpentineLayout == false) {
  93.     if (kMatrixVertical == false) {
  94.       i = (y * kMatrixWidth) + x;
  95.     } else {
  96.       i = kMatrixHeight * (kMatrixWidth - (x+1))+y;
  97.     }
  98.   }

  99.   if( kMatrixSerpentineLayout == true) {
  100.     if (kMatrixVertical == false) {
  101.       if( y & 0x01) {
  102.         // Odd rows run backwards
  103.         uint8_t reverseX = (kMatrixWidth - 1) - x;
  104.         i = (y * kMatrixWidth) + reverseX;
  105.       } else {
  106.         // Even rows run forwards
  107.         i = (y * kMatrixWidth) + x;
  108.       }
  109.     } else { // vertical positioning
  110.       if ( x & 0x01) {
  111.         i = kMatrixHeight * (kMatrixWidth - (x+1))+y;
  112.       } else {
  113.         i = kMatrixHeight * (kMatrixWidth - x) - (y+1);
  114.       }
  115.     }
  116.   }
  117.   
  118.   return i;
  119. }


  120. // Once you've gotten the basics working (AND NOT UNTIL THEN!)
  121. // here's a helpful technique that can be tricky to set up, but
  122. // then helps you avoid the needs for sprinkling array-bound-checking
  123. // throughout your code.
  124. //
  125. // It requires a careful attention to get it set up correctly, but
  126. // can potentially make your code smaller and faster.
  127. //
  128. // Suppose you have an 8 x 5 matrix of 40 LEDs.  Normally, you'd
  129. // delcare your leds array like this:
  130. //    CRGB leds[40];
  131. // But instead of that, declare an LED buffer with one extra pixel in
  132. // it, "leds_plus_safety_pixel".  Then declare "leds" as a pointer to
  133. // that array, but starting with the 2nd element (id=1) of that array:
  134. //    CRGB leds_with_safety_pixel[41];
  135. //    CRGB* const leds( leds_plus_safety_pixel + 1);
  136. // Then you use the "leds" array as you normally would.
  137. // Now "leds[0..N]" are aliases for "leds_plus_safety_pixel[1..(N+1)]",
  138. // AND leds[-1] is now a legitimate and safe alias for leds_plus_safety_pixel[0].
  139. // leds_plus_safety_pixel[0] aka leds[-1] is now your "safety pixel".
  140. //
  141. // Now instead of using the XY function above, use the one below, "XYsafe".
  142. //
  143. // If the X and Y values are 'in bounds', this function will return an index
  144. // into the visible led array, same as "XY" does.
  145. // HOWEVER -- and this is the trick -- if the X or Y values
  146. // are out of bounds, this function will return an index of -1.
  147. // And since leds[-1] is actually just an alias for leds_plus_safety_pixel[0],
  148. // it's a totally safe and legal place to access.  And since the 'safety pixel'
  149. // falls 'outside' the visible part of the LED array, anything you write
  150. // there is hidden from view automatically.
  151. // Thus, this line of code is totally safe, regardless of the actual size of
  152. // your matrix:
  153. //    leds[ XYsafe( random8(), random8() ) ] = CHSV( random8(), 255, 255);
  154. //
  155. // The only catch here is that while this makes it safe to read from and
  156. // write to 'any pixel', there's really only ONE 'safety pixel'.  No matter
  157. // what out-of-bounds coordinates you write to, you'll really be writing to
  158. // that one safety pixel.  And if you try to READ from the safety pixel,
  159. // you'll read whatever was written there last, reglardless of what coordinates
  160. // were supplied.

  161. #define NUM_LEDS (kMatrixWidth * kMatrixHeight)
  162. CRGB leds_plus_safety_pixel[ NUM_LEDS + 1];
  163. CRGB* const leds( leds_plus_safety_pixel + 1);

  164. uint16_t XYsafe( uint8_t x, uint8_t y)
  165. {
  166.   if( x >= kMatrixWidth) return -1;
  167.   if( y >= kMatrixHeight) return -1;
  168.   return XY(x,y);
  169. }


  170. // Demo that USES "XY" follows code below

  171. void loop()
  172. {
  173.     uint32_t ms = millis();
  174.     int32_t yHueDelta32 = ((int32_t)cos16( ms * (27/1) ) * (350 / kMatrixWidth));
  175.     int32_t xHueDelta32 = ((int32_t)cos16( ms * (39/1) ) * (310 / kMatrixHeight));
  176.     DrawOneFrame( ms / 65536, yHueDelta32 / 32768, xHueDelta32 / 32768);
  177.     if( ms < 5000 ) {
  178.       FastLED.setBrightness( scale8( BRIGHTNESS, (ms * 256) / 5000));
  179.     } else {
  180.       FastLED.setBrightness(BRIGHTNESS);
  181.     }
  182.     FastLED.show();
  183. }

  184. void DrawOneFrame( uint8_t startHue8, int8_t yHueDelta8, int8_t xHueDelta8)
  185. {
  186.   uint8_t lineStartHue = startHue8;
  187.   for( uint8_t y = 0; y < kMatrixHeight; y++) {
  188.     lineStartHue += yHueDelta8;
  189.     uint8_t pixelHue = lineStartHue;      
  190.     for( uint8_t x = 0; x < kMatrixWidth; x++) {
  191.       pixelHue += xHueDelta8;
  192.       leds[ XY(x, y)]  = CHSV( pixelHue, 255, 255);
  193.     }
  194.   }
  195. }


  196. void setup() {
  197.   FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalSMD5050);
  198.   FastLED.setBrightness( BRIGHTNESS );
  199. }
复制代码


 楼主| 发表于 2021-9-18 09:25 | 显示全部楼层
实验场景图

20.jpg
 楼主| 发表于 2021-12-15 08:51 | 显示全部楼层
【花雕动手做】有趣好玩的音乐可视化系列小项目(10)---WS2812硬板屏
项目之一:使用Adafruit_NeoPixel库的音乐可视化多彩节奏灯

实验开源代码

  1. /*
  2.   【花雕动手做】有趣好玩的音乐可视化系列小项目(10)---WS2812硬板屏
  3.   项目之一:使用Adafruit_NeoPixel库的音乐可视化多彩节奏灯
  4. */

  5. #include <Adafruit_NeoPixel.h>
  6. #define MIC A0 // 麦克风与A0相连接
  7. #define LED_PIN 6 // LED are connected to D6
  8. #define N_PIXELS 16 // Number of LED
  9. #define N 100 //样本数
  10. #define fadeDelay 10 // 淡出量
  11. #define noiseLevel 40 // 降噪下限

  12. Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_PIXELS, LED_PIN, NEO_GRB + NEO_KHZ800);

  13. int samples[N]; // 存储样本
  14. int periodFactor = 0; // 用于周期计算
  15. int t1 = -1;
  16. int T;
  17. int slope;
  18. byte periodChanged = 0;

  19. void setup() {
  20.   // Serial.begin(9600);
  21.   strip.begin();
  22.   ledsOff();
  23.   delay(500);
  24.   displayColor(Wheel(100));
  25.   strip.show();
  26.   delay(500);
  27. }

  28. void loop() {
  29.   Samples();
  30. }

  31. void Samples() {
  32.   for (int i = 0; i < N; i++) {
  33.     samples[i] = analogRead(0);
  34.     if (i > 0) {
  35.       slope = samples[i] - samples[i - 1];
  36.     }
  37.     else {
  38.       slope = samples[i] - samples[N - 1];
  39.     }

  40.     if (abs(slope) > noiseLevel) {
  41.       if (slope < 0) {
  42.         calculatePeriod(i);
  43.         if (periodChanged == 1) {
  44.           displayColor(getColor(T));
  45.         }
  46.       }
  47.     }
  48.     else {
  49.       ledsOff();
  50.     }
  51.     periodFactor += 1;
  52.     delay(1);
  53.   }
  54. }

  55. void calculatePeriod(int i) {
  56.   if (t1 == -1) {

  57.     t1 = i;
  58.   }
  59.   else {

  60.     int period = periodFactor * (i - t1);
  61.     periodChanged = T == period ? 0 : 1;
  62.     T = period;
  63.     // Serial.println(T);

  64.     t1 = i;
  65.     periodFactor = 0;
  66.   }
  67. }

  68. uint32_t getColor(int period) {
  69.   if (period == -1)
  70.     return Wheel(0);
  71.   else if (period > 400)
  72.     return Wheel(5);
  73.   else
  74.     return Wheel(map(-1 * period, -400, -1, 50, 255));
  75. }

  76. void fadeOut()
  77. {
  78.   for (int i = 0; i < 5; i++) {
  79.     strip.setBrightness(110 - i * 20);
  80.     strip.show(); // Update strip
  81.     delay(fadeDelay);
  82.     periodFactor += fadeDelay;
  83.   }
  84. }

  85. void fadeIn() {
  86.   strip.setBrightness(100);
  87.   strip.show();

  88.   for (int i = 0; i < 5; i++) {
  89.     //strip.setBrightness(20*i + 30);
  90.     //strip.show();
  91.     delay(fadeDelay);
  92.     periodFactor += fadeDelay;
  93.   }
  94. }

  95. void ledsOff() {
  96.   fadeOut();
  97.   for (int i = 0; i < N_PIXELS; i++) {
  98.     strip.setPixelColor(i, 0, 0, 0);
  99.   }
  100. }

  101. void displayColor(uint32_t color) {
  102.   for (int i = 0; i < N_PIXELS; i++) {
  103.     strip.setPixelColor(i, color);
  104.   }
  105.   fadeIn();
  106. }

  107. uint32_t Wheel(byte WheelPos) {
  108.   // Serial.println(WheelPos);
  109.   if (WheelPos < 85) {

  110.     return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
  111.   }
  112.   else if (WheelPos < 170) {
  113.     WheelPos -= 85;
  114.     return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  115.   }
  116.   else {
  117.     WheelPos -= 170;
  118.     return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  119.   }
  120. }
复制代码


 楼主| 发表于 2021-12-15 08:52 | 显示全部楼层
  实验场景图

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

本版积分规则

小黑屋|Archiver|手机版|Arduino爱好者

GMT+8, 2022-11-29 22:05 , Processed in 0.083273 second(s), 15 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表