1487浏览
查看: 1487|回复: 60

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

[复制链接]
37款传感器与模块的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止37种的。鉴于本人手头积累了一些传感器和执行器模块,依照实践出真知(一定要动手做)的理念,以学习和交流为目的,这里准备逐一动手试试多做实验,不管成功与否,都会记录下来——小小的进步或是搞不掂的问题,希望能够抛砖引玉。

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


01.jpg

每米30灯白底裸板

驴友花雕  初级技神
 楼主|

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

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

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


回复

使用道具 举报

驴友花雕  初级技神
 楼主|

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

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

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


回复

使用道具 举报

驴友花雕  初级技神
 楼主|

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

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

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


回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 15:22:39

本帖最后由 驴友花雕 于 2022-7-14 15:42 编辑

每米60灯黑底裸板


03.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 15:52:57

本帖最后由 驴友花雕 于 2022-7-14 15:56 编辑

WS2812B
是一个集控制电路与发光电路于一体的智能外控LED光源。其外型与一个5050LED灯珠相同,每个元件即为一个像素点。像素点内部包含了智能数字接口数据锁存信号整形放大驱动电路,还包含有高精度的内部振荡器和12V高压可编程定电流控制部分,有效保证了像素点光的颜色高度一致。数据协议采用单线归零码的通讯方式,像素点在上电复位以后,DIN端接受从控制器传输过来的数据,首先送过来的24bit数据被第一个像素点提取后,送到像素点内部的数据锁存器,剩余的数据经过内部整形处理电路整形放大后通过DO端口开始转发输出给下一个级联的像素点,每经过一个像素点的传输,信号减少24bit。像素点采用自动整形转发技术,使得该像素点的级联个数不受信号传送的限制,仅仅受限信号传输速度要求。

0-.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 15:59:20

0-0.jpg

01.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 16:00:53

02.jpg

02-.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 16:03:13

主要特点
1、智能反接保护,电源反接不会损坏IC。
2、IC控制电路与LED点光源公用一个电源。
3、控制电路与RGB芯片集成在一个5050封装的元器件中,构成一个完整的外控像素点。
4、内置信号整形电路,任何一个像素点收到信号后经过波形整形再输出,保证线路波形畸变不会累加。
5、内置上电复位和掉电复位电路。
6、每个像素点的三基色颜色可实现256级亮度显示,完成16777216种颜色的全真色彩显示,扫描频率不低于400Hz/s。
7、串行级联接口,能通过一根信号线完成数据的接收与解码。
8、任意两点传传输距离在不超过5米时无需增加任何电路。
9、当刷新速率30帧/秒时,级联数不小于1024点。
10、数据发送速度可达800Kbps。
11、光的颜色高度一致,性价比高。
应用领域
具有低电压驱动,环保节能,亮度高,散射角度大,一致性好,超低功率,超长寿命等优点。将控制电路集成于LED上面,电路变得更加简单,体积小,安装更加简便。主要应用领域,LED全彩发光字灯串,LED全彩模组, LED全彩软灯条硬灯条,LED护栏管。LED点光源,LED像素屏,LED异形屏,各种电子产品,电器设备跑马灯等。


02--.jpg

回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 16:23:36

02.jpg

04.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 16:25:07

06.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 16:26:16

07.jpg 05.jpg

回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 17:10:10

WS2812B是集控制电路和发光电路于一体的LED光源元件,其控制IC为WS2812B,发光元件是5050RGBLED,电压为5V,每个单位的峰值电流为60ma,灯带为三线制,VCC GND DIN分别为电源+、电源-、信号,当使用外部电源时,外部电源-需要与Arduino的GND相连。

07-0.jpg

07-.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 17:14:55

测试环境中可以直接使用Arduino的5V引脚直接供电,如果灯带长度过长,则需要外接电源。下为实验接线示意图。

08.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 17:17:12

本帖最后由 驴友花雕 于 2022-7-14 17:59 编辑

实验提示
1、可以在电源到地之间连接一个电容在 100uF 到 1000uF 之间的电容器,以平滑电源。
2、在 Arduino 数字输出引脚和条形数据输入引脚之间添加一个 220 或 470 Ohm 电阻器,以减少该线路上的噪声。
3、使arduino,电源和条带之间的电线尽可能短,以最大程度地减少电压损失。
4、如果您的灯条损坏且无法正常工作,请检查第一个 LED 是否损坏。如果是这样,剪掉它,重新焊接头针,它应该会再次工作。
5、WS2812 需要 5v 电源,每个 LED 在其全亮度下需要大约 60mA 电流。如果您的 LED 灯条有 30 个 LED,您需要 60mA x 30 = 1800 mA 或 1.8 Amp 电流。因此,您必须使用额定电流为 1.8 安培或更高的 5v 电源。

09.jpg

回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 18:05:31

打开Arduino IDE——工具——管理库,搜索并安装FastLED库

10.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

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

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

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序一:点亮ws2812灯带第一颗灯珠(红色闪烁)
  5. */
  6. #include <FastLED.h>
  7. #define NUM_LEDS 24
  8. #define DATA_PIN 6
  9. CRGB leds[NUM_LEDS];
  10. #define BRIGHTNESS  33
  11. void setup() {
  12.   FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  13. }
  14. void loop() {
  15.   leds[0] = CRGB::Red;
  16.   FastLED.show();
  17.   delay(500);
  18.   leds[0] = CRGB::Black;
  19.   FastLED.show();
  20.   delay(500);
  21. }
复制代码


回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 18:39:31

实验场景图  动态图

动画19.gif
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 18:57:20

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

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序二:点亮ws2812灯带三颗灯珠(红绿蓝色)
  5. */
  6. #include <FastLED.h>
  7. #define DATA_PIN    6
  8. #define NUM_LEDS    24
  9. #define BRIGHTNESS  33
  10. #define LED_TYPE    WS2812B
  11. #define COLOR_ORDER GRB
  12. CRGB leds[NUM_LEDS];
  13. #define UPDATES_PER_SECOND 100
  14. void setup() {
  15.   FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  16.   FastLED.setBrightness(BRIGHTNESS);
  17. }
  18. void loop() {
  19.   leds[0] = CRGB::Red;
  20.   leds[1] = CRGB::Green;
  21.   leds[2] = CRGB::Blue;
  22.   FastLED.show();
  23.   delay(10);
  24. }
复制代码


回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 19:01:43

实验场景图

05.jpg
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 19:13:34

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

  1. /*
  2.   【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
  3.   实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
  4.   实验程序三:循环变色的幻彩灯带(24颗灯珠)
  5. */
  6. #include <FastLED.h>
  7. #define NUM_LEDS 24
  8. #define DATA_PIN 6
  9. CRGB leds[NUM_LEDS];
  10. void setup() {
  11.   FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
  12.   FastLED.setBrightness(33);
  13. }
  14. void fadeall() {
  15.   for (int i = 0; i < NUM_LEDS; i++) {
  16.     leds[i].nscale8(250);
  17.   }
  18. }
  19. void loop() {
  20.   static uint8_t hue = 0;
  21.   for (int i = 0; i < NUM_LEDS; i++) {
  22.     leds[i] = CHSV(hue++, 255, 255);
  23.     FastLED.show();
  24.     fadeall();
  25.     delay(10);
  26.   }
  27.   for (int i = (NUM_LEDS) - 1; i >= 0; i--) {
  28.     leds[i] = CHSV(hue++, 255, 255);
  29.     FastLED.show();
  30.     fadeall();
  31.     delay(10);
  32.   }
  33. }
复制代码


回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 19:20:29

实验场景图  动态图

动画20.gif
回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 20:01:31

解释代码
在这里你可以看到我们首先包含了 FastLED 库。然后我们定义一些变量供以后使用。我们将使用该DATA_PIN变量来保存连接到 WS2812B LED 灯条的 Arduino 引脚号。

同样,我们NUM_LEDS用来保存您的 LED 灯条所拥有的 LED 数量。

BRIGHTNESS来控制 LED 的亮度。您可以设置 0 到 255 之间的任何亮度级别。

LED_TYPE将设置 LED 驱动器的类型。

COLOR_ORDER将设置您的 LED 驱动器的颜色顺序。

CRGB leds[NUM_LEDS];将创建一个名为 LEDs 的数组,该数组可以保存所需 LED 数量的 RGB 数据。

现在在设置部分,我们将设置我们的 LED 灯条。

  1. FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
复制代码

这告诉库我们正在使用连接到 Arduino 引脚 6 的 WS2812B LED 灯条,并且驱动程序有一个 GRB LED 订单。并且灯条有 24 个 WS2812B RGB LED。


回复

使用道具 举报

驴友花雕  初级技神
 楼主|

发表于 2022-7-14 20:06:14

设置 RGB 颜色


我们可以通过不同的方式设置 LED 的 RGB 值。在这里,我们将看看一些流行的。

示例 1:分别从红色、绿色和蓝色分量中设置颜色

  1. leds[i].red =    50;
  2. leds[i].green = 100;
  3. leds[i].blue =  150;
  4. // ...or, using the shorter synonyms "r", "g", and "b"...
  5. leds[i].r = 50;
  6. leds[i].g = 100;
  7. leds[i].b = 150;
复制代码


示例 2:一次从红色、绿色和蓝色分量中设置颜色。

  1. leds[i] = CRGB( 50, 100, 150);
复制代码


示例 3:通过“十六进制颜色代码”(0xRRGGBB)设置颜色

  1. leds[i] = 0xFF007F;
复制代码


示例 4:通过任何命名的 HTML 网页颜色设置颜色

  1. leds[i] = CRGB::HotPink;
复制代码


示例 5:通过 setRGB 设置颜色

  1. leds[i].setRGB( 50, 100, 150);
复制代码


将 CRGB 颜色从一个像素复制到另一个像素

  1. leds[i] = leds[j];
复制代码


回复

使用道具 举报

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

本版积分规则

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

硬件清单

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

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

mail