楼主: eagler8

[教程] 【Arduino】108种传感器模块系列实验(61)---WS2812直条8位模块

[复制链接]

签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 08:25 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  项目二十八:二维 XY 像素矩阵闪烁灯

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  3.   实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  4.   项目二十八:二维 XY 像素矩阵闪烁灯
  5. */

  6. #include <FastLED.h>

  7. #define LED_PIN  5

  8. #define COLOR_ORDER GRB
  9. #define CHIPSET     WS2811

  10. #define BRIGHTNESS 33

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


  26. // Params for width and height
  27. const uint8_t kMatrixWidth = 16;
  28. const uint8_t kMatrixHeight = 16;

  29. // Param for different pixel layouts
  30. const bool    kMatrixSerpentineLayout = true;
  31. const bool    kMatrixVertical = false;

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


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

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


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

  156. #define NUM_LEDS (kMatrixWidth * kMatrixHeight)
  157. CRGB leds_plus_safety_pixel[ NUM_LEDS + 1];
  158. CRGB* const leds( leds_plus_safety_pixel + 1);

  159. uint16_t XYsafe( uint8_t x, uint8_t y)
  160. {
  161.   if( x >= kMatrixWidth) return -1;
  162.   if( y >= kMatrixHeight) return -1;
  163.   return XY(x,y);
  164. }


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

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

  179. void DrawOneFrame( uint8_t startHue8, int8_t yHueDelta8, int8_t xHueDelta8)
  180. {
  181.   uint8_t lineStartHue = startHue8;
  182.   for( uint8_t y = 0; y < kMatrixHeight; y++) {
  183.     lineStartHue += yHueDelta8;
  184.     uint8_t pixelHue = lineStartHue;      
  185.     for( uint8_t x = 0; x < kMatrixWidth; x++) {
  186.       pixelHue += xHueDelta8;
  187.       leds[ XY(x, y)]  = CHSV( pixelHue, 255, 255);
  188.     }
  189.   }
  190. }


  191. void setup() {
  192.   FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalSMD5050);
  193.   FastLED.setBrightness( BRIGHTNESS );
  194. }
复制代码


签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 10:10 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  项目二十九:使用NeoPixelBrightnessBus库将循环亮度从高到低

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  3.   实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  4.   项目二十九:使用NeoPixelBrightnessBus库将循环亮度从高到低
  5. */

  6. // NeoPixelBrightness
  7. // This example will cycle brightness from high to low of
  8. // three pixels colored Red, Green, Blue.
  9. // This demonstrates the use of the NeoPixelBrightnessBus
  10. // with integrated brightness support
  11. //
  12. // There is serial output of the current state so you can
  13. // confirm and follow along
  14. //

  15. #include <NeoPixelBrightnessBus.h> // instead of NeoPixelBus.h

  16. const uint16_t PixelCount = 8; // this example assumes 3 pixels, making it smaller will cause a failure
  17. const uint8_t PixelPin = 6;  // make sure to set this to the correct pin, ignored for Esp8266

  18. #define colorSaturation 255 // saturation of color constants
  19. RgbColor red(colorSaturation, 0, 0);
  20. RgbColor green(0, colorSaturation, 0);
  21. RgbColor blue(0, 0, colorSaturation);

  22. // Make sure to provide the correct color order feature
  23. // for your NeoPixels
  24. NeoPixelBrightnessBus<NeoRgbFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);

  25. // you loose the original color the lower the dim value used
  26. // here due to quantization
  27. const uint8_t c_MinBrightness = 8;
  28. const uint8_t c_MaxBrightness = 255;

  29. int8_t direction; // current direction of dimming

  30. void setup()
  31. {
  32.   Serial.begin(115200);
  33.   while (!Serial); // wait for serial attach

  34.   Serial.println();
  35.   Serial.println("Initializing...");
  36.   Serial.flush();

  37.   // this resets all the neopixels to an off state
  38.   strip.Begin();
  39.   strip.Show();

  40.   direction = -1; // default to dim first

  41.   Serial.println();
  42.   Serial.println("Running...");

  43.   // set our three original colors
  44.   strip.SetPixelColor(0, red);
  45.   strip.SetPixelColor(1, green);
  46.   strip.SetPixelColor(2, blue);
  47.   strip.SetPixelColor(3, red);
  48.   strip.SetPixelColor(4, green);
  49.   strip.SetPixelColor(5, blue);
  50.   strip.SetPixelColor(6, red);
  51.   strip.SetPixelColor(7, green);

  52.   strip.Show();
  53. }


  54. void loop()
  55. {
  56.   uint8_t brightness = strip.GetBrightness();
  57.   Serial.println(brightness);

  58.   delay(50);

  59.   // swap diection of dim when limits are reached
  60.   //
  61.   if (direction < 0 && brightness <= c_MinBrightness)
  62.   {
  63.     direction = 1;
  64.   }
  65.   else if (direction > 0 && brightness >= c_MaxBrightness)
  66.   {
  67.     direction = -1;
  68.   }
  69.   // apply dimming
  70.   brightness += direction;
  71.   strip.SetBrightness(brightness);
  72.   // show the results
  73.   strip.Show();
  74. }
复制代码


签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 10:12 | 显示全部楼层
实验串口返回情况

19.jpg

签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 10:18 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  项目三十:显示具有伽马校正的定时系列颜色渐变

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  3.   实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  4.   项目三十:显示具有伽马校正的定时系列颜色渐变
  5. */

  6. // NeoPixelGamma
  7. // This example will display a timed series of color gradiants with gamma correction
  8. // and then without.
  9. // If the last pixel is on, then the colors being shown are color corrected.
  10. // It will show Red grandiant, Green grandiant, Blue grandiant, a White grandiant, and
  11. // then repeat.
  12. //
  13. // This will demonstrate the use of the NeoGamma class
  14. //
  15. //

  16. #include <NeoPixelBus.h>
  17. #include <NeoPixelAnimator.h>

  18. const uint16_t PixelCount = 8; // make sure to set this to the number of pixels in your strip
  19. const uint8_t PixelPin = 6;  // make sure to set this to the correct pin, ignored for Esp8266

  20. NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);
  21. // for esp8266 omit the pin
  22. //NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount);

  23. // uncomment only one of these to compare memory use or speed
  24. //
  25. // NeoGamma<NeoGammaEquationMethod> colorGamma;
  26. NeoGamma<NeoGammaTableMethod> colorGamma;

  27. void DrawPixels(bool corrected, HslColor startColor, HslColor stopColor)
  28. {
  29.     for (uint16_t index = 0; index < strip.PixelCount() - 1; index++)
  30.     {
  31.         float progress = index / static_cast<float>(strip.PixelCount() - 2);
  32.         RgbColor color = HslColor::LinearBlend<NeoHueBlendShortestDistance>(startColor, stopColor, progress);
  33.         if (corrected)
  34.         {
  35.             color = colorGamma.Correct(color);
  36.         }
  37.         strip.SetPixelColor(index, color);
  38.     }

  39.     // use the last pixel to indicate if we are showing corrected colors or not
  40.     if (corrected)
  41.     {
  42.         strip.SetPixelColor(strip.PixelCount() - 1, RgbColor(64));
  43.     }
  44.     else
  45.     {
  46.         strip.SetPixelColor(strip.PixelCount() - 1, RgbColor(0));
  47.     }

  48.     strip.Show();
  49. }

  50. void setup()
  51. {
  52.     strip.Begin();
  53.     strip.Show();
  54. }

  55. void loop()
  56. {
  57.     HslColor startColor;
  58.     HslColor stopColor;

  59.     // red color
  60.     startColor = HslColor(0.0f, 1.0f, 0.0f);
  61.     stopColor = HslColor(0.0f, 1.0f, 0.5f);
  62.     DrawPixels(true, startColor, stopColor);
  63.     delay(2000);
  64.     DrawPixels(false, startColor, stopColor);
  65.     delay(2000);

  66.     // green color
  67.     startColor = HslColor(0.33f, 1.0f, 0.0f);
  68.     stopColor = HslColor(0.33f, 1.0f, 0.5f);
  69.     DrawPixels(true, startColor, stopColor);
  70.     delay(2000);
  71.     DrawPixels(false, startColor, stopColor);
  72.     delay(2000);

  73.     // blue color
  74.     startColor = HslColor(0.66f, 1.0f, 0.0f);
  75.     stopColor = HslColor(0.66f, 1.0f, 0.5f);
  76.     DrawPixels(true, startColor, stopColor);
  77.     delay(2000);
  78.     DrawPixels(false, startColor, stopColor);
  79.     delay(2000);

  80.     // white color
  81.     startColor = HslColor(0.0f, 0.0f, 0.0f);
  82.     stopColor = HslColor(0.0f, 0.0f, 0.5f);
  83.     DrawPixels(true, startColor, stopColor);
  84.     delay(2000);
  85.     DrawPixels(false, startColor, stopColor);
  86.     delay(2000);
  87. }
复制代码


签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 10:24 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  项目三十一:像素测试:将四个像素显示为红色、绿色、蓝色、白色之间循环

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  3.   实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  4.   项目三十一:像素测试:将四个像素显示为红色、绿色、蓝色、白色之间循环
  5. */

  6. // NeoPixelTest
  7. // This example will cycle between showing four pixels as Red, Green, Blue, White
  8. // and then showing those pixels as Black.
  9. //
  10. // Included but commented out are examples of configuring a NeoPixelBus for
  11. // different color order including an extra white channel, different data speeds, and
  12. // for Esp8266 different methods to send the data.
  13. // NOTE: You will need to make sure to pick the one for your platform
  14. //
  15. //
  16. // There is serial output of the current state so you can confirm and follow along
  17. //

  18. #include <NeoPixelBus.h>

  19. const uint16_t PixelCount = 8; // this example assumes 4 pixels, making it smaller will cause a failure
  20. const uint8_t PixelPin = 6;  // make sure to set this to the correct pin, ignored for Esp8266

  21. #define colorSaturation 128

  22. // three element pixels, in different order and speeds
  23. NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);
  24. //NeoPixelBus<NeoRgbFeature, Neo400KbpsMethod> strip(PixelCount, PixelPin);

  25. // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use.
  26. // There are other Esp8266 alternative methods that provide more pin options, but also have
  27. // other side effects.
  28. // for details see wiki linked here https://github.com/Makuna/NeoPixelBus/wiki/ESP8266-NeoMethods

  29. // You can also use one of these for Esp8266,
  30. // each having their own restrictions
  31. //
  32. // These two are the same as above as the DMA method is the default
  33. // NOTE: These will ignore the PIN and use GPI03 pin
  34. //NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> strip(PixelCount, PixelPin);
  35. //NeoPixelBus<NeoRgbFeature, NeoEsp8266Dma400KbpsMethod> strip(PixelCount, PixelPin);

  36. // Uart method is good for the Esp-01 or other pin restricted modules
  37. // for details see wiki linked here https://github.com/Makuna/NeoPixelBus/wiki/ESP8266-NeoMethods
  38. // NOTE: These will ignore the PIN and use GPI02 pin
  39. //NeoPixelBus<NeoGrbFeature, NeoEsp8266Uart1800KbpsMethod> strip(PixelCount, PixelPin);
  40. //NeoPixelBus<NeoRgbFeature, NeoEsp8266Uart1400KbpsMethod> strip(PixelCount, PixelPin);

  41. // The bitbang method is really only good if you are not using WiFi features of the ESP
  42. // It works with all but pin 16
  43. //NeoPixelBus<NeoGrbFeature, NeoEsp8266BitBang800KbpsMethod> strip(PixelCount, PixelPin);
  44. //NeoPixelBus<NeoRgbFeature, NeoEsp8266BitBang400KbpsMethod> strip(PixelCount, PixelPin);

  45. // four element pixels, RGBW
  46. //NeoPixelBus<NeoRgbwFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);

  47. RgbColor red(colorSaturation, 0, 0);
  48. RgbColor green(0, colorSaturation, 0);
  49. RgbColor blue(0, 0, colorSaturation);
  50. RgbColor white(colorSaturation);
  51. RgbColor black(0);

  52. HslColor hslRed(red);
  53. HslColor hslGreen(green);
  54. HslColor hslBlue(blue);
  55. HslColor hslWhite(white);
  56. HslColor hslBlack(black);


  57. void setup()
  58. {
  59.   Serial.begin(115200);
  60.   while (!Serial); // wait for serial attach

  61.   Serial.println();
  62.   Serial.println("Initializing...");
  63.   Serial.flush();

  64.   // this resets all the neopixels to an off state
  65.   strip.Begin();
  66.   strip.Show();


  67.   Serial.println();
  68.   Serial.println("Running...");
  69. }


  70. void loop()
  71. {
  72.   delay(5000);

  73.   Serial.println("Colors R, G, B, W...");

  74.   // set the colors,
  75.   // if they don't match in order, you need to use NeoGrbFeature feature
  76.   strip.SetPixelColor(0, red);
  77.   strip.SetPixelColor(1, green);
  78.   strip.SetPixelColor(2, blue);
  79.   strip.SetPixelColor(3, white);
  80.   strip.SetPixelColor(4, red);
  81.   strip.SetPixelColor(5, green);
  82.   strip.SetPixelColor(6, blue);
  83.   strip.SetPixelColor(7, white);
  84.   // the following line demonstrates rgbw color support
  85.   // if the NeoPixels are rgbw types the following line will compile
  86.   // if the NeoPixels are anything else, the following line will give an error
  87.   //strip.SetPixelColor(3, RgbwColor(colorSaturation));
  88.   strip.Show();


  89.   delay(2000);

  90.   Serial.println("Off ...");

  91.   // turn off the pixels
  92.   strip.SetPixelColor(0, black);
  93.   strip.SetPixelColor(1, black);
  94.   strip.SetPixelColor(2, black);
  95.   strip.SetPixelColor(3, black);
  96.   strip.Show();

  97.   delay(2000);

  98.   Serial.println("HSL Colors R, G, B, W...");

  99.   // set the colors,
  100.   // if they don't match in order, you may need to use NeoGrbFeature feature
  101.   strip.SetPixelColor(0, hslRed);
  102.   strip.SetPixelColor(1, hslGreen);
  103.   strip.SetPixelColor(2, hslBlue);
  104.   strip.SetPixelColor(3, hslWhite);
  105.   strip.Show();


  106.   delay(2000);

  107.   Serial.println("Off again...");

  108.   // turn off the pixels
  109.   strip.SetPixelColor(0, hslBlack);
  110.   strip.SetPixelColor(1, hslBlack);
  111.   strip.SetPixelColor(2, hslBlack);
  112.   strip.SetPixelColor(3, hslBlack);
  113.   strip.Show();

  114. }
复制代码




签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 10:26 | 显示全部楼层
实验串口返回情况

20.jpg

签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 10:40 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  项目三十二:为每个像素随机选择一种新颜色并设置动画

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  3.   实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  4.   项目三十二:为每个像素随机选择一种新颜色并设置动画
  5. */

  6. // NeoPixelAnimation
  7. // This example will randomly pick a new color for each pixel and animate
  8. // the current color to the new color over a random small amount of time, using
  9. // a randomly selected animation curve.
  10. // It will repeat this process once all pixels have finished the animation
  11. //
  12. // This will demonstrate the use of the NeoPixelAnimator extended time feature.
  13. // This feature allows for different time scales to be used, allowing slow extended
  14. // animations to be created.
  15. //
  16. // This will demonstrate the use of the NeoEase animation ease methods; that provide
  17. // simulated acceleration to the animations.
  18. //
  19. // It also includes platform specific code for Esp8266 that demonstrates easy
  20. // animation state and function definition inline.  This is not available on AVR
  21. // Arduinos; but the AVR compatible code is also included for comparison.
  22. //
  23. // The example includes some serial output that you can follow along with as it
  24. // does the animation.
  25. //

  26. #include <NeoPixelBus.h>
  27. #include <NeoPixelAnimator.h>

  28. const uint16_t PixelCount = 8; // make sure to set this to the number of pixels in your strip
  29. const uint8_t PixelPin = 6;  // make sure to set this to the correct pin, ignored for Esp8266

  30. NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);
  31. // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use.  
  32. // There are other Esp8266 alternative methods that provide more pin options, but also have
  33. // other side effects.
  34. // for details see wiki linked here https://github.com/Makuna/NeoPixelBus/wiki/ESP8266-NeoMethods

  35. // NeoPixel animation time management object
  36. NeoPixelAnimator animations(PixelCount, NEO_CENTISECONDS);

  37. // create with enough animations to have one per pixel, depending on the animation
  38. // effect, you may need more or less.
  39. //
  40. // since the normal animation time range is only about 65 seconds, by passing timescale value
  41. // to the NeoPixelAnimator constructor we can increase the time range, but we also increase
  42. // the time between the animation updates.   
  43. // NEO_CENTISECONDS will update the animations every 100th of a second rather than the default
  44. // of a 1000th of a second, but the time range will now extend from about 65 seconds to about
  45. // 10.9 minutes.  But you must remember that the values passed to StartAnimations are now
  46. // in centiseconds.
  47. //
  48. // Possible values from 1 to 32768, and there some helpful constants defined as...
  49. // NEO_MILLISECONDS        1    // ~65 seconds max duration, ms updates
  50. // NEO_CENTISECONDS       10    // ~10.9 minutes max duration, centisecond updates
  51. // NEO_DECISECONDS       100    // ~1.8 hours max duration, decisecond updates
  52. // NEO_SECONDS          1000    // ~18.2 hours max duration, second updates
  53. // NEO_DECASECONDS     10000    // ~7.5 days, 10 second updates
  54. //

  55. #if defined(NEOPIXEBUS_NO_STL)
  56. // for AVR, you need to manage the state due to lack of STL/compiler support
  57. // for Esp8266 you can define the function using a lambda and state is created for you
  58. // see below for an example
  59. struct MyAnimationState
  60. {
  61.     RgbColor StartingColor;  // the color the animation starts at
  62.     RgbColor EndingColor; // the color the animation will end at
  63.     AnimEaseFunction Easeing; // the acceleration curve it will use
  64. };

  65. MyAnimationState animationState[PixelCount];
  66. // one entry per pixel to match the animation timing manager

  67. void AnimUpdate(const AnimationParam& param)
  68. {
  69.     // first apply an easing (curve) to the animation
  70.     // this simulates acceleration to the effect
  71.     float progress = animationState[param.index].Easeing(param.progress);

  72.     // this gets called for each animation on every time step
  73.     // progress will start at 0.0 and end at 1.0
  74.     // we use the blend function on the RgbColor to mix
  75.     // color based on the progress given to us in the animation
  76.     RgbColor updatedColor = RgbColor::LinearBlend(
  77.         animationState[param.index].StartingColor,
  78.         animationState[param.index].EndingColor,
  79.         progress);
  80.     // apply the color to the strip
  81.     strip.SetPixelColor(param.index, updatedColor);
  82. }
  83. #endif

  84. void SetRandomSeed()
  85. {
  86.     uint32_t seed;

  87.     // random works best with a seed that can use 31 bits
  88.     // analogRead on a unconnected pin tends toward less than four bits
  89.     seed = analogRead(0);
  90.     delay(1);

  91.     for (int shifts = 3; shifts < 31; shifts += 3)
  92.     {
  93.         seed ^= analogRead(0) << shifts;
  94.         delay(1);
  95.     }

  96.     // Serial.println(seed);
  97.     randomSeed(seed);
  98. }

  99. void setup()
  100. {
  101.     Serial.begin(115200);
  102.     while (!Serial); // wait for serial attach

  103.     strip.Begin();
  104.     strip.Show();

  105.     SetRandomSeed();

  106.     // just pick some colors
  107.     for (uint16_t pixel = 0; pixel < PixelCount; pixel++)
  108.     {
  109.         RgbColor color = RgbColor(random(255), random(255), random(255));
  110.         strip.SetPixelColor(pixel, color);
  111.     }

  112.     Serial.println();
  113.     Serial.println("Running...");
  114. }


  115. void SetupAnimationSet()
  116. {
  117.     // setup some animations
  118.     for (uint16_t pixel = 0; pixel < PixelCount; pixel++)
  119.     {
  120.         const uint8_t peak = 128;

  121.         // pick a random duration of the animation for this pixel
  122.         // since values are centiseconds, the range is 1 - 4 seconds
  123.         uint16_t time = random(100, 400);

  124.         // each animation starts with the color that was present
  125.         RgbColor originalColor = strip.GetPixelColor(pixel);
  126.         // and ends with a random color
  127.         RgbColor targetColor = RgbColor(random(peak), random(peak), random(peak));
  128.         // with the random ease function
  129.         AnimEaseFunction easing;

  130.         switch (random(3))
  131.         {
  132.         case 0:
  133.             easing = NeoEase::CubicIn;
  134.             break;
  135.         case 1:
  136.             easing = NeoEase::CubicOut;
  137.             break;
  138.         case 2:
  139.             easing = NeoEase::QuadraticInOut;
  140.             break;
  141.         }

  142. #if defined(NEOPIXEBUS_NO_STL)
  143.         // each animation starts with the color that was present
  144.         animationState[pixel].StartingColor = originalColor;
  145.         // and ends with a random color
  146.         animationState[pixel].EndingColor = targetColor;
  147.         // using the specific curve
  148.         animationState[pixel].Easeing = easing;

  149.         // now use the animation state we just calculated and start the animation
  150.         // which will continue to run and call the update function until it completes
  151.         animations.StartAnimation(pixel, time, AnimUpdate);
  152. #else
  153.         // we must supply a function that will define the animation, in this example
  154.         // we are using "lambda expression" to define the function inline, which gives
  155.         // us an easy way to "capture" the originalColor and targetColor for the call back.
  156.         //
  157.         // this function will get called back when ever the animation needs to change
  158.         // the state of the pixel, it will provide a animation progress value
  159.         // from 0.0 (start of animation) to 1.0 (end of animation)
  160.         //
  161.         // we use this progress value to define how we want to animate in this case
  162.         // we call RgbColor::LinearBlend which will return a color blended between
  163.         // the values given, by the amount passed, hich is also a float value from 0.0-1.0.
  164.         // then we set the color.
  165.         //
  166.         // There is no need for the MyAnimationState struct as the compiler takes care
  167.         // of those details for us
  168.         AnimUpdateCallback animUpdate = [=](const AnimationParam& param)
  169.         {
  170.             // progress will start at 0.0 and end at 1.0
  171.             // we convert to the curve we want
  172.             float progress = easing(param.progress);

  173.             // use the curve value to apply to the animation
  174.             RgbColor updatedColor = RgbColor::LinearBlend(originalColor, targetColor, progress);
  175.             strip.SetPixelColor(pixel, updatedColor);
  176.         };

  177.         // now use the animation properties we just calculated and start the animation
  178.         // which will continue to run and call the update function until it completes
  179.         animations.StartAnimation(pixel, time, animUpdate);
  180. #endif
  181.     }
  182. }

  183. void loop()
  184. {
  185.     if (animations.IsAnimating())
  186.     {
  187.         // the normal loop just needs these two to run the active animations
  188.         animations.UpdateAnimations();
  189.         strip.Show();
  190.     }
  191.     else
  192.     {
  193.         Serial.println();
  194.         Serial.println("Setup Next Set...");
  195.         // example function that sets up some animations
  196.         SetupAnimationSet();
  197.     }
  198. }
复制代码


签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 10:42 | 显示全部楼层
实验串口返回情况

21.jpg

签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 10:48 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  项目三十三:NeoEase 动画缓动方法的使用;提供模拟加速动画

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  3.   实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  4.   项目三十三:NeoEase 动画缓动方法的使用;提供模拟加速动画
  5. */

  6. // NeoPixelCylon
  7. // This example will move a Cylon Red Eye back and forth across the
  8. // the full collection of pixels on the strip.
  9. //
  10. // This will demonstrate the use of the NeoEase animation ease methods; that provide
  11. // simulated acceleration to the animations.
  12. //
  13. //

  14. #include <NeoPixelBus.h>
  15. #include <NeoPixelAnimator.h>

  16. const uint16_t PixelCount = 8; // make sure to set this to the number of pixels in your strip
  17. const uint8_t PixelPin = 6;  // make sure to set this to the correct pin, ignored for Esp8266
  18. const RgbColor CylonEyeColor(HtmlColor(0x7f0000));

  19. NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);
  20. // for esp8266 omit the pin
  21. //NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount);

  22. NeoPixelAnimator animations(2); // only ever need 2 animations

  23. uint16_t lastPixel = 0; // track the eye position
  24. int8_t moveDir = 1; // track the direction of movement

  25. // uncomment one of the lines below to see the effects of
  26. // changing the ease function on the movement animation
  27. AnimEaseFunction moveEase =
  28. //      NeoEase::Linear;
  29. //      NeoEase::QuadraticInOut;
  30. //      NeoEase::CubicInOut;
  31.         NeoEase::QuarticInOut;
  32. //      NeoEase::QuinticInOut;
  33. //      NeoEase::SinusoidalInOut;
  34. //      NeoEase::ExponentialInOut;
  35. //      NeoEase::CircularInOut;

  36. void FadeAll(uint8_t darkenBy)
  37. {
  38.     RgbColor color;
  39.     for (uint16_t indexPixel = 0; indexPixel < strip.PixelCount(); indexPixel++)
  40.     {
  41.         color = strip.GetPixelColor(indexPixel);
  42.         color.Darken(darkenBy);
  43.         strip.SetPixelColor(indexPixel, color);
  44.     }
  45. }

  46. void FadeAnimUpdate(const AnimationParam& param)
  47. {
  48.     if (param.state == AnimationState_Completed)
  49.     {
  50.         FadeAll(10);
  51.         animations.RestartAnimation(param.index);
  52.     }
  53. }

  54. void MoveAnimUpdate(const AnimationParam& param)
  55. {
  56.     // apply the movement animation curve
  57.     float progress = moveEase(param.progress);

  58.     // use the curved progress to calculate the pixel to effect
  59.     uint16_t nextPixel;
  60.     if (moveDir > 0)
  61.     {
  62.         nextPixel = progress * PixelCount;
  63.     }
  64.     else
  65.     {
  66.         nextPixel = (1.0f - progress) * PixelCount;
  67.     }

  68.     // if progress moves fast enough, we may move more than
  69.     // one pixel, so we update all between the calculated and
  70.     // the last
  71.     if (lastPixel != nextPixel)
  72.     {
  73.         for (uint16_t i = lastPixel + moveDir; i != nextPixel; i += moveDir)
  74.         {
  75.             strip.SetPixelColor(i, CylonEyeColor);
  76.         }
  77.     }
  78.     strip.SetPixelColor(nextPixel, CylonEyeColor);

  79.     lastPixel = nextPixel;

  80.     if (param.state == AnimationState_Completed)
  81.     {
  82.         // reverse direction of movement
  83.         moveDir *= -1;

  84.         // done, time to restart this position tracking animation/timer
  85.         animations.RestartAnimation(param.index);
  86.     }
  87. }

  88. void SetupAnimations()
  89. {
  90.     // fade all pixels providing a tail that is longer the faster
  91.     // the pixel moves.
  92.     animations.StartAnimation(0, 5, FadeAnimUpdate);

  93.     // take several seconds to move eye fron one side to the other
  94.     animations.StartAnimation(1, 2000, MoveAnimUpdate);
  95. }

  96. void setup()
  97. {
  98.     strip.Begin();
  99.     strip.Show();

  100.     SetupAnimations();
  101. }

  102. void loop()
  103. {
  104.     // this is all that is needed to keep it running
  105.     // and avoiding using delay() is always a good thing for
  106.     // any timing related routines
  107.     animations.UpdateAnimations();
  108.     strip.Show();
  109. }
复制代码


签到天数: 506 天

[LV.9]以坛为家II

 楼主| 发表于 2021-9-17 11:16 | 显示全部楼层
  【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  项目三十四:将随机选择一种颜色并将所有像素淡化为该颜色,然后
  它会将它们淡化为黑色并重新开始

  实验开源代码

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+图形编程+仿真编程)
  3.   实验六十一:直条8位 WS2812B 5050 RGB LED内置全彩驱动彩灯模块
  4.   项目三十四:将随机选择一种颜色并将所有像素淡化为该颜色,然后
  5.   它会将它们淡化为黑色并重新开始
  6. */

  7. #include <NeoPixelBus.h>
  8. #include <NeoPixelAnimator.h>

  9. const uint16_t PixelCount = 8; // make sure to set this to the number of pixels in your strip
  10. const uint8_t PixelPin = 6;  // make sure to set this to the correct pin, ignored for Esp8266
  11. const uint8_t AnimationChannels = 1; // we only need one as all the pixels are animated at once

  12. NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);
  13. // For Esp8266, the Pin is omitted and it uses GPIO3 due to DMA hardware use.
  14. // There are other Esp8266 alternative methods that provide more pin options, but also have
  15. // other side effects.
  16. // for details see wiki linked here https://github.com/Makuna/NeoPixelBus/wiki/ESP8266-NeoMethods

  17. NeoPixelAnimator animations(AnimationChannels); // NeoPixel animation management object

  18. boolean fadeToColor = true;  // general purpose variable used to store effect state


  19. // what is stored for state is specific to the need, in this case, the colors.
  20. // basically what ever you need inside the animation update function
  21. struct MyAnimationState
  22. {
  23.   RgbColor StartingColor;
  24.   RgbColor EndingColor;
  25. };

  26. // one entry per pixel to match the animation timing manager
  27. MyAnimationState animationState[AnimationChannels];

  28. void SetRandomSeed()
  29. {
  30.   uint32_t seed;

  31.   // random works best with a seed that can use 31 bits
  32.   // analogRead on a unconnected pin tends toward less than four bits
  33.   seed = analogRead(0);
  34.   delay(1);

  35.   for (int shifts = 3; shifts < 31; shifts += 3)
  36.   {
  37.     seed ^= analogRead(0) << shifts;
  38.     delay(1);
  39.   }

  40.   randomSeed(seed);
  41. }

  42. // simple blend function
  43. void BlendAnimUpdate(const AnimationParam& param)
  44. {
  45.   // this gets called for each animation on every time step
  46.   // progress will start at 0.0 and end at 1.0
  47.   // we use the blend function on the RgbColor to mix
  48.   // color based on the progress given to us in the animation
  49.   RgbColor updatedColor = RgbColor::LinearBlend(
  50.                             animationState[param.index].StartingColor,
  51.                             animationState[param.index].EndingColor,
  52.                             param.progress);

  53.   // apply the color to the strip
  54.   for (uint16_t pixel = 0; pixel < PixelCount; pixel++)
  55.   {
  56.     strip.SetPixelColor(pixel, updatedColor);
  57.   }
  58. }

  59. void FadeInFadeOutRinseRepeat(float luminance)
  60. {
  61.   if (fadeToColor)
  62.   {
  63.     // Fade upto a random color
  64.     // we use HslColor object as it allows us to easily pick a hue
  65.     // with the same saturation and luminance so the colors picked
  66.     // will have similiar overall brightness
  67.     RgbColor target = HslColor(random(360) / 360.0f, 1.0f, luminance);
  68.     uint16_t time = random(800, 2000);

  69.     animationState[0].StartingColor = strip.GetPixelColor(0);
  70.     animationState[0].EndingColor = target;

  71.     animations.StartAnimation(0, time, BlendAnimUpdate);
  72.   }
  73.   else
  74.   {
  75.     // fade to black
  76.     uint16_t time = random(600, 700);

  77.     animationState[0].StartingColor = strip.GetPixelColor(0);
  78.     animationState[0].EndingColor = RgbColor(0);

  79.     animations.StartAnimation(0, time, BlendAnimUpdate);
  80.   }

  81.   // toggle to the next effect state
  82.   fadeToColor = !fadeToColor;
  83. }

  84. void setup()
  85. {
  86.   strip.Begin();
  87.   strip.Show();

  88.   SetRandomSeed();
  89. }

  90. void loop()
  91. {
  92.   if (animations.IsAnimating())
  93.   {
  94.     // the normal loop just needs these two to run the active animations
  95.     animations.UpdateAnimations();
  96.     strip.Show();
  97.   }
  98.   else
  99.   {
  100.     // no animation runnning, start some
  101.     //
  102.     FadeInFadeOutRinseRepeat(0.2f); // 0.0 = black, 0.25 is normal, 0.5 is bright
  103.   }
  104. }
复制代码


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

本版积分规则

热门推荐

原价299元【语音开发板套件】限时免费领!
原价299元【语音开发板套
教你让OLED动起来!多重字符串版!
教你让OLED动起来!多重字
大家都知道:arduino单片机是单线程的 而上次教程中的多段字符串的运行速度必须一致
TTGO T8 1.7.1使用TFT_eSPI库驱动2.4寸ILI9341屏幕显示板载SD内图片
TTGO T8 1.7.1使用TFT_eSP
TTGO T8 1.7.1采用Espressif官方ESP32-WROVER模块制作,4MB闪存和8MB PSRAM,支持TF
TTGO TFT屏幕Arduino使用的小结
TTGO TFT屏幕Arduino使用
TTGO TFT屏幕是一款ESP32和1.44寸LCD屏幕组合的产品,屏幕由ST7789驱动。ESP32自带520
分享我的第一个点灯程序——家庭控制中心
分享我的第一个点灯程序—
2020年,在B站上初识ESP8266,被ESP8266的低门槛、高性价比深深吸引,2020年6月20日,
Copyright   ©2015-2016  Arduino中文社区  Powered by©Discuz!   
快速回复 返回顶部 返回列表