驴友花雕 发表于 2022-7-14 15:18:29

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

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

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




每米30灯白底裸板

驴友花雕 发表于 2022-7-18 09:13:43

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

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

#include <Adafruit_NeoPixel.h>
#include <FastLED.h>
#include <EEPROM.h>
#define PIN 6
#define N_PIXELS24
#define BG 0
#define COLOR_ORDER GRB// Try mixing up the letters (RGB, GBR, BRG, etc) for a whole new world of color combinations
#define BRIGHTNESS 50   // 0-255, higher number is brighter.
#define LED_TYPE WS2812B
#define MIC_PIN   A4// Microphone is attached to this analog pin
#define DC_OFFSET10// DC offset in mic signal - if unusure, leave 0
#define NOISE   10// Noise/hum/interference in mic signal
#define SAMPLES   60// Length of buffer for dynamic level adjustment
#define TOP       (N_PIXELS + 2) // Allow dot to go slightly off scale
#define PEAK_FALL 20// Rate of peak falling dot
#define N_PIXELS_HALF (N_PIXELS/2)
#define GRAVITY         -9.81            // Downward (negative) acceleration of gravity in m/s^2
#define h0                1                  // Starting height, in meters, of the ball (strip length)
#define NUM_BALLS         3                  // Number of bouncing balls you want (recommend < 7, but 20 is fun in its own way)
#define SPEED .20       // Amount to increment RGB color by each cycle
int brightnessPin = A0, potPin = A1;
//config for balls
float h ;                         // An array of heights
float vImpact0 = sqrt( -2 * GRAVITY * h0 );// Impact velocity of the ball when it hits the ground if "dropped" from the top of the strip
float vImpact ;                   // As time goes on the impact velocity will change, so make an array to store those values
float tCycle ;                  // The time since the last time the ball struck the ground
int   pos ;                     // The integer position of the dot on the strip (LED index)
longtLast ;                     // The clock time of the last ground strike
float COR ;                     // Coefficient of Restitution (bounce damping)

float
greenOffset = 30,
blueOffset = 150;

byte
peak      = 0,      // Used for falling dot
dotCount= 0,      // Frame counter for delaying dot-falling speed
volCount= 0;      // Frame counter for storing past volume data
int
vol,       // Collection of prior volume samples
lvl       = 10,      // Current "dampened" audio level
minLvlAvg = 0,      // For dynamic adjustment of graph low & high
maxLvlAvg = 512;

int brightnessValue, prevBrightnessValue;
int sensorDeviationBrightness = 1;
int sensitivityValue = 128;                               // 0 - 255, initial value (value read from the potentiometer if useSensorValues = true)
int maxSensitivity = 2 * 255;                           // let the 'volume' go up to 200%!
int ledBrightness = 255;                                 // 0 - 255, initial value (value read from the potentiometer if useSensorValues = true)
int val;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_PIXELS, PIN, NEO_GRB + NEO_KHZ800);

// FOR SYLON ETC
uint8_t thisbeat =23;
uint8_t thatbeat =28;
uint8_t thisfade =   2;                                     // How quickly does it fade? Lower = slower fade rate.
uint8_t thissat = 255;                                     // The saturation, where 255 = brilliant colours.
uint8_t thisbri = 255;

//FOR JUGGLE
uint8_t numdots = 4;                                          // Number of dots in use.
uint8_t faderate = 2;                                       // How long should the trails be. Very low value = longer trails.
uint8_t hueinc = 16;                                          // Incremental change in hue between each dot.
uint8_t thishue = 0;                                          // Starting hue.
uint8_t curhue = 0;
uint8_t thisbright = 255;                                     // How bright should the LED/display be.
uint8_t basebeat = 5;
uint8_t max_bright = 255;

// Twinkle
float redStates;
float blueStates;
float greenStates;
float Fade = 0.96;

// Vu meter 4
const uint32_t Red = strip.Color(255, 0, 0);
const uint32_t Yellow = strip.Color(255, 255, 0);
const uint32_t Green = strip.Color(0, 255, 0);
const uint32_t Blue = strip.Color(0, 0, 255);
const uint32_t White = strip.Color(255, 255, 255);
const uint32_t Dark = strip.Color(0, 0, 0);
unsigned int sample;

CRGB leds;

int          myhue =   0;


// constants used here to set pin numbers:
const int buttonPin = 3;   // the number of the pushbutton pin

// Variables will change:

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;

//Ripple variables
int color;
int center = 0;
int step = -1;
int maxSteps = 8;
float fadeRate = 0.80;
int diff;

//background color
uint32_t currentBg = random(256);
uint32_t nextBg = currentBg;

void setup() {
delay( 2000 ); // power-up safety delay
FastLED.addLeds<WS2812B, PIN, COLOR_ORDER>(leds, N_PIXELS).setCorrection( TypicalLEDStrip );
FastLED.setBrightness(BRIGHTNESS );
analogReference(EXTERNAL);
memset(vol, 0, sizeof(vol));
LEDS.addLeds<LED_TYPE, PIN, COLOR_ORDER>(leds, N_PIXELS);
strip.begin();
strip.show(); // Initialize all pixels to 'off'

   
//initialize the serial port
Serial.begin(115200);
   pinMode(buttonPin, INPUT);
    pinMode(2, OUTPUT);
//initialize the buttonPin as output
digitalWrite(buttonPin, HIGH);
digitalWrite(2, HIGH);

for (int i = 0 ; i < NUM_BALLS ; i++) {    // Initialize variables
    tLast = millis();
    h = h0;
    pos = 0;                              // Balls start on the ground
    vImpact = vImpact0;                   // And "pop" up at vImpact0
    tCycle = 0;
    COR = 0.90 - float(i)/pow(NUM_BALLS,2);
}
}

void loop() {

   brightnessValue = analogRead(brightnessPin);
brightnessValue = map(brightnessValue, 0, 1023, 0, 255);

if (abs(brightnessValue - prevBrightnessValue) > sensorDeviationBrightness) {
    ledBrightness = brightnessValue;
    strip.setBrightness(ledBrightness);
    prevBrightnessValue = brightnessValue;
}

   //for mic
uint8_ti;
uint16_t minLvl, maxLvl;
int      n, height;
// end mic
buttonPushCounter=EEPROM.read(0);
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
    // compare the buttonState to its previous state
if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes:");
      Serial.println(buttonPushCounter);
      if(buttonPushCounter>=14) {
      buttonPushCounter=1;}
      EEPROM.write(0,buttonPushCounter);
      
    }
    else {
      // if the current state is LOW then the button
      // wend from on to off:
      Serial.println("off");
    }
}
// save the current state as the last state,
//for next time through the loop

lastButtonState = buttonState;

switch (buttonPushCounter){
         
case 1:
   buttonPushCounter==1; {
      vu(); // Red
   break;}
      
case 2:
   buttonPushCounter==2; {
       vu2(); // Red
      break;}
      
   case 3:
   buttonPushCounter==3; {
    Vu3(); //
      break;}
         
    case 4:
   buttonPushCounter==4; {
    Vu4(); //
      break;}
      
       case 5:
   buttonPushCounter==5; {
      rainbow(150);
       break;}
      
      case 6:
   buttonPushCounter==6; {
      rainbow(20);
       break;}
      
         case 7:
   buttonPushCounter==7; {
      ripple();
       break;}
      
         case 8:
   buttonPushCounter==8; {
      ripple2();
       break;}
      
            case 9:
   buttonPushCounter==9; {
      Twinkle();
       break;}
      
         case 10:
   buttonPushCounter==10; {
      pattern2();
       break;}
      
         case 11:
   buttonPushCounter==11; {
      pattern3();
       break;}
      
         case 12:
   buttonPushCounter==12; {
    Balls(); //
      break;}   
      
      case 13:
   buttonPushCounter==13; {
    colorWipe(strip.Color(0, 0, 0), 10); // A Black
      break;}
         
   }

}

void colorWipe(uint32_t c, uint8_t wait) {
for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      if (digitalRead(buttonPin) != lastButtonState)// <------------- add this
       return;         // <------------ and this
      delay(wait);
}
}
void Vu4() {
    uint8_ti;
uint16_t minLvl, maxLvl;
int      n, height;


val = (analogRead(potPin));
val= map(val, 0, 1023, -10, 6);

n   = analogRead(MIC_PIN);                        // Raw reading from mic
n   = abs(n - 0 - DC_OFFSET); // Center on zero
n   = (n <= NOISE) ? 0 : (n - NOISE);             // Remove noise/hum

    if(val<0){
      n=n/(val*(-1));
      }
       if(val>0){
      n=n*val;
      }

lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)

// Calculate bar height based on dynamic min/max levels (fixed point):
height = TOP * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);

if(height < 0L)       height = 0;      // Clip output
else if(height > TOP) height = TOP;
if(height > peak)   peak   = height; // Keep 'peak' dot at top
greenOffset += SPEED;
blueOffset += SPEED;
if (greenOffset >= 255) greenOffset = 0;
if (blueOffset >= 255) blueOffset = 0;

// Color pixels based on rainbow gradient
for(i=0; i<N_PIXELS_HALF; i++) {
    if(i >= height) {            
      strip.setPixelColor(N_PIXELS_HALF-i-1,   0,   0, 0);
      strip.setPixelColor(N_PIXELS_HALF+i,   0,   0, 0);
    }
    else {
      uint32_t color = Wheel(map(i,0,N_PIXELS_HALF-1,(int)greenOffset, (int)blueOffset));
      strip.setPixelColor(N_PIXELS_HALF-i-1,color);
      strip.setPixelColor(N_PIXELS_HALF+i,color);
    }
   
}

// Draw peak dot
if(peak > 0 && peak <= N_PIXELS_HALF-1) {
    uint32_t color = Wheel(map(peak,0,N_PIXELS_HALF-1,30,150));
    strip.setPixelColor(N_PIXELS_HALF-peak-1,color);
    strip.setPixelColor(N_PIXELS_HALF+peak,color);
}

   strip.show(); // Update strip

// Every few frames, make the peak pixel drop by 1:

    if(++dotCount >= PEAK_FALL) { //fall rate
      
      if(peak > 0) peak--;
      dotCount = 0;
    }

vol = n;                      // Save sample for dynamic leveling
if(++volCount >= SAMPLES) volCount = 0; // Advance/rollover sample counter

// Get volume range of prior frames
minLvl = maxLvl = vol;
for(i=1; i<SAMPLES; i++) {
    if(vol < minLvl)      minLvl = vol;
    else if(vol > maxLvl) maxLvl = vol;
}
// minLvl and maxLvl indicate the volume range over prior frames, used
// for vertically scaling the output graph (so it looks interesting
// regardless of volume level).If they're too close together though
// (e.g. at very low volume levels) the graph becomes super coarse
// and 'jumpy'...so keep some minimum distance between them (this
// also lets the graph go to zero when no sound is playing):
if((maxLvl - minLvl) < TOP) maxLvl = minLvl + TOP;
minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)
}

void Vu3() {
uint8_t i;
uint16_t minLvl, maxLvl;
int n, height;

val = (analogRead(potPin));
val= map(val, 0, 1023, -10, 6);

n = analogRead(MIC_PIN);             // Raw reading from mic
n = abs(n - 0 - DC_OFFSET);      // Center on zero
n = (n <= NOISE) ? 0 : (n - NOISE);// Remove noise/hum

      if(val<0){
      n=n/(val*(-1));
      }
       if(val>0){
      n=n*val;
      }
      
lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)

// Calculate bar height based on dynamic min/max levels (fixed point):
height = TOP * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);

if (height < 0L)       height = 0;      // Clip output
else if (height > TOP) height = TOP;
if (height > peak)   peak   = height; // Keep 'peak' dot at top

greenOffset += SPEED;
blueOffset += SPEED;
if (greenOffset >= 255) greenOffset = 0;
if (blueOffset >= 255) blueOffset = 0;

// Color pixels based on rainbow gradient
for (i = 0; i < N_PIXELS; i++) {
    if (i >= height) {
      strip.setPixelColor(i, 0, 0, 0);
    } else {
      strip.setPixelColor(i, Wheel(
      map(i, 0, strip.numPixels() - 1, (int)greenOffset, (int)blueOffset)
      ));
    }
}
// Draw peak dot
if(peak > 0 && peak <= N_PIXELS-1) strip.setPixelColor(peak,Wheel(map(peak,0,strip.numPixels()-1,30,150)));

   strip.show(); // Update strip

// Every few frames, make the peak pixel drop by 1:

    if(++dotCount >= PEAK_FALL) { //fall rate
      
      if(peak > 0) peak--;
      dotCount = 0;
    }
strip.show();// Update strip

vol = n;
if (++volCount >= SAMPLES) {
    volCount = 0;
}

// Get volume range of prior frames
minLvl = maxLvl = vol;
for (i = 1; i < SAMPLES; i++) {
    if (vol < minLvl) {
      minLvl = vol;
    } else if (vol > maxLvl) {
      maxLvl = vol;
    }
}

// minLvl and maxLvl indicate the volume range over prior frames, used
// for vertically scaling the output graph (so it looks interesting
// regardless of volume level).If they're too close together though
// (e.g. at very low volume levels) the graph becomes super coarse
// and 'jumpy'...so keep some minimum distance between them (this
// also lets the graph go to zero when no sound is playing):
if ((maxLvl - minLvl) < TOP) {
    maxLvl = minLvl + TOP;
}
minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)
}


void Balls() {
for (int i = 0 ; i < NUM_BALLS ; i++) {
    tCycle =millis() - tLast ;   // Calculate the time since the last time the ball was on the ground

    // A little kinematics equation calculates positon as a function of time, acceleration (gravity) and intial velocity
    h = 0.5 * GRAVITY * pow( tCycle/1000 , 2.0 ) + vImpact * tCycle/1000;

    if ( h < 0 ) {                     
      h = 0;                            // If the ball crossed the threshold of the "ground," put it back on the ground
      vImpact = COR * vImpact ;   // and recalculate its new upward velocity as it's old velocity * COR
      tLast = millis();

      if ( vImpact < 0.01 ) vImpact = vImpact0;// If the ball is barely moving, "pop" it back up at vImpact0
    }
    pos = round( h * (N_PIXELS - 1) / h0);       // Map "h" to a "pos" integer index position on the LED strip
}

//Choose color of LEDs, then the "pos" LED on
for (int i = 0 ; i < NUM_BALLS ; i++) leds] = CHSV( uint8_t (i * 40) , 255, 255);
FastLED.show();
//Then off for the next loop around
for (int i = 0 ; i < NUM_BALLS ; i++) {
    leds] = CRGB::Black;
}
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
uint16_t i, j;

for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
   if (digitalRead(buttonPin) != lastButtonState)// <------------- add this
       return;         // <------------ and this
      delay(wait);
      }
    }
// HERE

void vu() {

uint8_ti;
uint16_t minLvl, maxLvl;
int      n, height;

val = (analogRead(potPin));
val= map(val, 0, 1023, -10, 6);

n   = analogRead(MIC_PIN);                        // Raw reading from mic
n   = abs(n - 0 - DC_OFFSET); // Center on zero
n   = (n <= NOISE) ? 0 : (n - NOISE);             // Remove noise/hum
   if(val<0){
      n=n/(val*(-1));
      }
       if(val>0){
      n=n*val;
      }
lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)

// Calculate bar height based on dynamic min/max levels (fixed point):
height = TOP * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);

if(height < 0L)       height = 0;      // Clip output
else if(height > TOP) height = TOP;
if(height > peak)   peak   = height; // Keep 'peak' dot at top


// Color pixels based on rainbow gradient
for(i=0; i<N_PIXELS; i++) {
    if(i >= height)               strip.setPixelColor(i,   0,   0, 0);
    else strip.setPixelColor(i,Wheel(map(i,0,strip.numPixels()-1,30,150)));   
}

// Draw peak dot
if(peak > 0 && peak <= N_PIXELS-1) strip.setPixelColor(peak,Wheel(map(peak,0,strip.numPixels()-1,30,150)));

   strip.show(); // Update strip

// Every few frames, make the peak pixel drop by 1:

    if(++dotCount >= PEAK_FALL) { //fall rate
      
      if(peak > 0) peak--;
      dotCount = 0;
    }

vol = n;                      // Save sample for dynamic leveling
if(++volCount >= SAMPLES) volCount = 0; // Advance/rollover sample counter

// Get volume range of prior frames
minLvl = maxLvl = vol;
for(i=1; i<SAMPLES; i++) {
    if(vol < minLvl)      minLvl = vol;
    else if(vol > maxLvl) maxLvl = vol;
}
// minLvl and maxLvl indicate the volume range over prior frames, used
// for vertically scaling the output graph (so it looks interesting
// regardless of volume level).If they're too close together though
// (e.g. at very low volume levels) the graph becomes super coarse
// and 'jumpy'...so keep some minimum distance between them (this
// also lets the graph go to zero when no sound is playing):
if((maxLvl - minLvl) < TOP) maxLvl = minLvl + TOP;
minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)

}

// Input a value 0 to 255 to get a color value.
// The colors are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
if(WheelPos < 85) {
   return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
} else if(WheelPos < 170) {
   WheelPos -= 85;
   return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
} else {
   WheelPos -= 170;
   return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
}

void vu2() {

uint8_ti;
uint16_t minLvl, maxLvl;
int      n, height;

val = (analogRead(potPin));
val= map(val, 0, 1023, -10, 6);
n   = analogRead(MIC_PIN);                        // Raw reading from mic
n   = abs(n - 0 - DC_OFFSET); // Center on zero
n   = (n <= NOISE) ? 0 : (n - NOISE);             // Remove noise/hum

      if(val<0){
      n=n/(val*(-1));
      }
       if(val>0){
      n=n*val;
      }
lvl = ((lvl * 7) + n) >> 3;    // "Dampened" reading (else looks twitchy)

// Calculate bar height based on dynamic min/max levels (fixed point):
height = TOP * (lvl - minLvlAvg) / (long)(maxLvlAvg - minLvlAvg);

if(height < 0L)       height = 0;      // Clip output
else if(height > TOP) height = TOP;
if(height > peak)   peak   = height; // Keep 'peak' dot at top


// Color pixels based on rainbow gradient
for(i=0; i<N_PIXELS_HALF; i++) {
    if(i >= height) {            
      strip.setPixelColor(N_PIXELS_HALF-i-1,   0,   0, 0);
      strip.setPixelColor(N_PIXELS_HALF+i,   0,   0, 0);
    }
    else {
      uint32_t color = Wheel(map(i,0,N_PIXELS_HALF-1,30,150));
      strip.setPixelColor(N_PIXELS_HALF-i-1,color);
      strip.setPixelColor(N_PIXELS_HALF+i,color);
    }
}

// Draw peak dot
if(peak > 0 && peak <= N_PIXELS_HALF-1) {
    uint32_t color = Wheel(map(peak,0,N_PIXELS_HALF-1,30,150));
    strip.setPixelColor(N_PIXELS_HALF-peak-1,color);
    strip.setPixelColor(N_PIXELS_HALF+peak,color);
}

   strip.show(); // Update strip

// Every few frames, make the peak pixel drop by 1:

    if(++dotCount >= PEAK_FALL) { //fall rate
      
      if(peak > 0) peak--;
      dotCount = 0;
    }

vol = n;                      // Save sample for dynamic leveling
if(++volCount >= SAMPLES) volCount = 0; // Advance/rollover sample counter

// Get volume range of prior frames
minLvl = maxLvl = vol;
for(i=1; i<SAMPLES; i++) {
    if(vol < minLvl)      minLvl = vol;
    else if(vol > maxLvl) maxLvl = vol;
}
// minLvl and maxLvl indicate the volume range over prior frames, used
// for vertically scaling the output graph (so it looks interesting
// regardless of volume level).If they're too close together though
// (e.g. at very low volume levels) the graph becomes super coarse
// and 'jumpy'...so keep some minimum distance between them (this
// also lets the graph go to zero when no sound is playing):
if((maxLvl - minLvl) < TOP) maxLvl = minLvl + TOP;
minLvlAvg = (minLvlAvg * 63 + minLvl) >> 6; // Dampen min/max levels
maxLvlAvg = (maxLvlAvg * 63 + maxLvl) >> 6; // (fake rolling average)
}

//here................

void ripple() {

    if (currentBg == nextBg) {
      nextBg = random(256);
    }
    else if (nextBg > currentBg) {
      currentBg++;
    } else {
      currentBg--;
    }
    for(uint16_t l = 0; l < N_PIXELS; l++) {
      leds = CHSV(currentBg, 255, 50);         // strip.setPixelColor(l, Wheel(currentBg, 0.1));
    }

if (step == -1) {
    center = random(N_PIXELS);
    color = random(256);
    step = 0;
}

if (step == 0) {
    leds = CHSV(color, 255, 255);         // strip.setPixelColor(center, Wheel(color, 1));
    step ++;
}
else {
    if (step < maxSteps) {
      Serial.println(pow(fadeRate,step));

      leds = CHSV(color, 255, pow(fadeRate, step)*255);       //   strip.setPixelColor(wrap(center + step), Wheel(color, pow(fadeRate, step)));
      leds = CHSV(color, 255, pow(fadeRate, step)*255);       //   strip.setPixelColor(wrap(center - step), Wheel(color, pow(fadeRate, step)));
      if (step > 3) {
      leds = CHSV(color, 255, pow(fadeRate, step - 2)*255);   //   strip.setPixelColor(wrap(center + step - 3), Wheel(color, pow(fadeRate, step - 2)));
      leds = CHSV(color, 255, pow(fadeRate, step - 2)*255);   //   strip.setPixelColor(wrap(center - step + 3), Wheel(color, pow(fadeRate, step - 2)));
      }
      step ++;
    }
    else {
      step = -1;
    }
}

LEDS.show();
delay(50);
}

int wrap(int step) {
if(step < 0) return N_PIXELS + step;
if(step > N_PIXELS - 1) return step - N_PIXELS;
return step;
}


void one_color_allHSV(int ahue, int abright) {                // SET ALL LEDS TO ONE COLOR (HSV)
for (int i = 0 ; i < N_PIXELS; i++ ) {
    leds = CHSV(ahue, 255, abright);
}
}

void ripple2() {
if (BG){
    if (currentBg == nextBg) {
      nextBg = random(256);
    }
    else if (nextBg > currentBg) {
      currentBg++;
    } else {
      currentBg--;
    }
    for(uint16_t l = 0; l < N_PIXELS; l++) {
      strip.setPixelColor(l, Wheel(currentBg, 0.1));
    }
} else {
    for(uint16_t l = 0; l < N_PIXELS; l++) {
      strip.setPixelColor(l, 0, 0, 0);
    }
}

if (step == -1) {
    center = random(N_PIXELS);
    color = random(256);
    step = 0;
}

if (step == 0) {
    strip.setPixelColor(center, Wheel(color, 1));
    step ++;
}
else {
    if (step < maxSteps) {
      strip.setPixelColor(wrap(center + step), Wheel(color, pow(fadeRate, step)));
      strip.setPixelColor(wrap(center - step), Wheel(color, pow(fadeRate, step)));
      if (step > 3) {
      strip.setPixelColor(wrap(center + step - 3), Wheel(color, pow(fadeRate, step - 2)));
      strip.setPixelColor(wrap(center - step + 3), Wheel(color, pow(fadeRate, step - 2)));
      }
      step ++;
    }
    else {
      step = -1;
    }
}

strip.show();
delay(50);
}
//int wrap(int step) {
//if(step < 0) return Pixels + step;
//if(step > Pixels - 1) return step - Pixels;
//return step;
//}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos, float opacity) {

if(WheelPos < 85) {
    return strip.Color((WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity, 0);
}
else if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color((255 - WheelPos * 3) * opacity, 0, (WheelPos * 3) * opacity);
}
else {
    WheelPos -= 170;
    return strip.Color(0, (WheelPos * 3) * opacity, (255 - WheelPos * 3) * opacity);
}
}

   void pattern2() {
      
       sinelon();                                                // Call our sequence.
show_at_max_brightness_for_power();                         // Power managed display of LED's.
} // loop()


void sinelon() {
// a colored dot sweeping back and forth, with fading trails
fadeToBlackBy( leds, N_PIXELS, thisfade);
int pos1 = beatsin16(thisbeat,0,N_PIXELS);
int pos2 = beatsin16(thatbeat,0,N_PIXELS);
    leds[(pos1+pos2)/2] += CHSV( myhue++/64, thissat, thisbri);
}
// Pattern 3 - JUGGLE
    void pattern3() {
       ChangeMe();
juggle();
show_at_max_brightness_for_power();                         // Power managed display of LED's.
} // loop()

void juggle() {                                             // Several colored dots, weaving in and out of sync with each other
curhue = thishue;                                          // Reset the hue values.
fadeToBlackBy(leds, N_PIXELS, faderate);
for( int i = 0; i < numdots; i++) {
    leds += CHSV(curhue, thissat, thisbright);   //beat16 is a FastLED 3.1 function
    curhue += hueinc;
}
} // juggle()

void ChangeMe() {                                             // A time (rather than loop) based demo sequencer. This gives us full control over the length of each sequence.
uint8_t secondHand = (millis() / 1000) % 30;                // IMPORTANT!!! Change '30' to a different value to change duration of the loop.
static uint8_t lastSecond = 99;                           // Static variable, means it's only defined once. This is our 'debounce' variable.
if (lastSecond != secondHand) {                           // Debounce to make sure we're not repeating an assignment.
    lastSecond = secondHand;
    if (secondHand ==0){numdots=1; faderate=2;}// You can change values here, one at a time , or altogether.
    if (secondHand == 10){numdots=4; thishue=128; faderate=8;}
    if (secondHand == 20){hueinc=48; thishue=random8();}                               // Only gets called once, and not continuously for the next several seconds. Therefore, no rainbows.
}
} // ChangeMe()

void Twinkle () {
   if (random(25) == 1) {
      uint16_t i = random(N_PIXELS);
      if (redStates < 1 && greenStates < 1 && blueStates < 1) {
      redStates = random(256);
      greenStates = random(256);
      blueStates = random(256);
      }
    }
   
    for(uint16_t l = 0; l < N_PIXELS; l++) {
      if (redStates > 1 || greenStates > 1 || blueStates > 1) {
      strip.setPixelColor(l, redStates, greenStates, blueStates);
      
      if (redStates > 1) {
          redStates = redStates * Fade;
      } else {
          redStates = 0;
      }
      
      if (greenStates > 1) {
          greenStates = greenStates * Fade;
      } else {
          greenStates = 0;
      }
      
      if (blueStates > 1) {
          blueStates = blueStates * Fade;
      } else {
          blueStates = 0;
      }
      
      } else {
      strip.setPixelColor(l, 0, 0, 0);
      }
    }
    strip.show();
   delay(10);

}

// TOO HERE

void rainbow(uint8_t wait) {
uint16_t i, j;

for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    // check if a button pressed
    if (digitalRead(buttonPin) != lastButtonState)// <------------- add this
       return;         // <------------ and this
    delay(wait);
}
}

驴友花雕 发表于 2022-7-17 12:59:27

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

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

#include "FastLED.h"
#define NUM_LEDS   24
#define LED_TYPE   WS2811
#define COLOR_ORDER   GRB
#define DATA_PIN      6
//#define CLK_PIN       4
#define VOLTS          12
#define MAX_MA       4000

CRGBArray<NUM_LEDS> leds;

#define TWINKLE_SPEED 7 //整体闪烁速度,0(非常慢)到 8(非常快)
#define TWINKLE_DENSITY 5 // 整体闪烁密度,0(NONE 点亮)到 8(ALL 一次点亮)
#define SECONDS_PER_PALETTE10 // 多久更换一次调色板

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

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

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


CRGBPalette16 gCurrentPalette;
CRGBPalette16 gTargetPalette;

void setup() {
delay( 1000 ); //safety startup delay
FastLED.setMaxPowerInVoltsAndMilliamps( VOLTS, MAX_MA);
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
    .setCorrection(TypicalLEDStrip);

chooseNextColorPalette(gTargetPalette);
}


void loop(){
EVERY_N_SECONDS( SECONDS_PER_PALETTE ) {
    chooseNextColorPalette( gTargetPalette );
}

EVERY_N_MILLISECONDS( 10 ) {
    nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 12);
}

drawTwinkles( leds);

FastLED.show();
}

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

uint32_t clock32 = millis();

// Set up the background color, "bg".
// if AUTO_SELECT_BACKGROUND_COLOR == 1, and the first two colors of
// the current palette are identical, then a deeply faded version of
// that color is used for the background color
CRGB bg;
if( (AUTO_SELECT_BACKGROUND_COLOR == 1) &&
      (gCurrentPalette == gCurrentPalette )) {
    bg = gCurrentPalette;
    uint8_t bglight = bg.getAverageLight();
    if( bglight > 64) {
      bg.nscale8_video( 16); // very bright, so scale to 1/16th
    } else if( bglight > 16) {
      bg.nscale8_video( 64); // not that bright, so scale to 1/4th
    } else {
      bg.nscale8_video( 86); // dim, scale to 1/3rd.
    }
} else {
    bg = gBackgroundColor; // just use the explicitly defined background color
}

uint8_t backgroundBrightness = bg.getAverageLight();

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

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

    uint8_t cbright = c.getAverageLight();
    int16_t deltabright = cbright - backgroundBrightness;
    if( deltabright >= 32 || (!bg)) {
      // If the new pixel is significantly brighter than the background color,
      // use the new color.
      pixel = c;
    } else if( deltabright > 0 ) {
      // If the new pixel is just slightly brighter than the background color,
      // mix a blend of the new color and the background color
      pixel = blend( bg, c, deltabright * 8);
    } else {
      // if the new pixel is not at all brighter than the background color,
      // just use the background color.
      pixel = bg;
    }
}
}


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

uint8_t bright = 0;
if( ((slowcycle8 & 0x0E)/2) < TWINKLE_DENSITY) {
    bright = attackDecayWave8( fastcycle8);
}

uint8_t hue = slowcycle8 - salt;
CRGB c;
if( bright > 0) {
    c = ColorFromPalette( gCurrentPalette, hue, bright, NOBLEND);
    if( COOL_LIKE_INCANDESCENT == 1 ) {
      coolLikeIncandescent( c, fastcycle8);
    }
} else {
    c = CRGB::Black;
}
return c;
}


// This function is like 'triwave8', which produces a
// symmetrical up-and-down triangle sawtooth waveform, except that this
// function produces a triangle wave with a faster attack and a slower decay:
//
//   / \
//    /   \
//   /         \
///             \
//

uint8_t attackDecayWave8( uint8_t i)
{
if( i < 86) {
    return i * 3;
} else {
    i -= 86;
    return 255 - (i + (i/2));
}
}

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

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

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

// A mostly (dark) green palette with red berries.
#define Holly_Green 0x00580c
#define Holly_Red   0xB00402
const TProgmemRGBPalette16 Holly_p FL_PROGMEM =
{Holly_Green, Holly_Green, Holly_Green, Holly_Green,
   Holly_Green, Holly_Green, Holly_Green, Holly_Green,
   Holly_Green, Holly_Green, Holly_Green, Holly_Green,
   Holly_Green, Holly_Green, Holly_Green, Holly_Red
};

// A red and white striped palette
// "CRGB::Gray" is used as white to keep the brightness more uniform.
const TProgmemRGBPalette16 RedWhite_p FL_PROGMEM =
{CRGB::Red,CRGB::Red,CRGB::Red,CRGB::Red,
   CRGB::Gray, CRGB::Gray, CRGB::Gray, CRGB::Gray,
   CRGB::Red,CRGB::Red,CRGB::Red,CRGB::Red,
   CRGB::Gray, CRGB::Gray, CRGB::Gray, CRGB::Gray };

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

// A pure "fairy light" palette with some brightness variations
#define HALFFAIRY ((CRGB::FairyLight & 0xFEFEFE) / 2)
#define QUARTERFAIRY ((CRGB::FairyLight & 0xFCFCFC) / 4)
const TProgmemRGBPalette16 FairyLight_p FL_PROGMEM =
{CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight,
   HALFFAIRY,      HALFFAIRY,      CRGB::FairyLight, CRGB::FairyLight,
   QUARTERFAIRY,   QUARTERFAIRY,   CRGB::FairyLight, CRGB::FairyLight,
   CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight, CRGB::FairyLight };

// A palette of soft snowflakes with the occasional bright one
const TProgmemRGBPalette16 Snow_p FL_PROGMEM =
{0x304048, 0x304048, 0x304048, 0x304048,
   0x304048, 0x304048, 0x304048, 0x304048,
   0x304048, 0x304048, 0x304048, 0x304048,
   0x304048, 0x304048, 0x304048, 0xE0F0FF };

// A palette reminiscent of large 'old-school' C9-size tree lights
// in the five classic colors: red, orange, green, blue, and white.
#define C9_Red    0xB80400
#define C9_Orange 0x902C02
#define C9_Green0x046002
#define C9_Blue   0x070758
#define C9_White0x606820
const TProgmemRGBPalette16 RetroC9_p FL_PROGMEM =
{C9_Red,    C9_Orange, C9_Red,    C9_Orange,
   C9_Orange, C9_Red,    C9_Orange, C9_Red,
   C9_Green,C9_Green,C9_Green,C9_Green,
   C9_Blue,   C9_Blue,   C9_Blue,
   C9_White
};

// A cold, icy pale blue palette
#define Ice_Blue1 0x0C1040
#define Ice_Blue2 0x182080
#define Ice_Blue3 0x5080C0
const TProgmemRGBPalette16 Ice_p FL_PROGMEM =
{
Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
Ice_Blue1, Ice_Blue1, Ice_Blue1, Ice_Blue1,
Ice_Blue2, Ice_Blue2, Ice_Blue2, Ice_Blue3
};


// Add or remove palette names from this list to control which color
// palettes are used, and in what order.
const TProgmemRGBPalette16* ActivePaletteList[] = {
&RetroC9_p,
&BlueWhite_p,
&RainbowColors_p,
&FairyLight_p,
&RedGreenWhite_p,
&PartyColors_p,
&RedWhite_p,
&Snow_p,
&Holly_p,
&Ice_p
};


// Advance to the next color palette in the list (above).
void chooseNextColorPalette( CRGBPalette16& pal)
{
const uint8_t numberOfPalettes = sizeof(ActivePaletteList) / sizeof(ActivePaletteList);
static uint8_t whichPalette = -1;
whichPalette = addmod8( whichPalette, 1, numberOfPalettes);

pal = *(ActivePaletteList);
}

驴友花雕 发表于 2022-7-17 16:37:12

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

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

#include <FastLED.h>

#define LED_PIN   6
#define BRIGHTNESS24
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB
#define BRIGHTNESS33

// Params for width and height
const uint8_t kMatrixWidth= 24;
const uint8_t kMatrixHeight = 1;

// Param for different pixel layouts
const bool    kMatrixSerpentineLayout = true;

#define NUM_LEDS (kMatrixWidth * kMatrixHeight)
#define MAX_DIMENSION ((kMatrixWidth>kMatrixHeight) ? kMatrixWidth : kMatrixHeight)

// The leds
CRGB leds;

// The 16 bit version of our coordinates
static uint16_t x;
static uint16_t y;
static uint16_t z;

// We're using the x/y dimensions to map to the x/y pixels on the matrix.We'll
// use the z-axis for "time".speed determines how fast time moves forward.Try
// 1 for a very slow moving effect, or 60 for something that ends up looking like
// water.
uint16_t speed = 20; // speed is set dynamically once we've started up

// Scale determines how far apart the pixels in our noise matrix are.Try
// changing these values around to see how it affects the motion of the display.The
// higher the value of scale, the more "zoomed out" the noise iwll be.A value
// of 1 will be so zoomed in, you'll mostly see solid colors.
uint16_t scale = 30; // scale is set dynamically once we've started up

// This is the array that we keep our computed noise values in
uint8_t noise;

CRGBPalette16 currentPalette( PartyColors_p );
uint8_t       colorLoop = 1;

void setup() {
delay(3000);
FastLED.addLeds<LED_TYPE,LED_PIN,COLOR_ORDER>(leds,NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);

// Initialize our coordinates to some random values
x = random16();
y = random16();
z = random16();
}

// Fill the x/y array of 8-bit noise values using the inoise8 function.
void fillnoise8() {
// If we're runing at a low "speed", some 8-bit artifacts become visible
// from frame-to-frame.In order to reduce this, we can do some fast data-smoothing.
// The amount of data smoothing we're doing depends on "speed".
uint8_t dataSmoothing = 0;
if( speed < 50) {
    dataSmoothing = 200 - (speed * 4);
}

for(int i = 0; i < MAX_DIMENSION; i++) {
    int ioffset = scale * i;
    for(int j = 0; j < MAX_DIMENSION; j++) {
      int joffset = scale * j;
      
      uint8_t data = inoise8(x + ioffset,y + joffset,z);

      // The range of the inoise8 function is roughly 16-238.
      // These two operations expand those values out to roughly 0..255
      // You can comment them out if you want the raw noise data.
      data = qsub8(data,16);
      data = qadd8(data,scale8(data,39));

      if( dataSmoothing ) {
      uint8_t olddata = noise;
      uint8_t newdata = scale8( olddata, dataSmoothing) + scale8( data, 256 - dataSmoothing);
      data = newdata;
      }
      
      noise = data;
    }
}

z += speed;

// apply slow drift to X and Y, just for visual variation.
x += speed / 8;
y -= speed / 16;
}

void mapNoiseToLEDsUsingPalette()
{
static uint8_t ihue=0;

for(int i = 0; i < kMatrixWidth; i++) {
    for(int j = 0; j < kMatrixHeight; j++) {
      // We use the value at the (i,j) coordinate in the noise
      // array for our brightness, and the flipped value from (j,i)
      // for our pixel's index into the color palette.

      uint8_t index = noise;
      uint8_t bri =   noise;

      // if this palette is a 'loop', add a slowly-changing base value
      if( colorLoop) {
      index += ihue;
      }

      // brighten up, as the color palette itself often contains the
      // light/dark dynamic range desired
      if( bri > 127 ) {
      bri = 255;
      } else {
      bri = dim8_raw( bri * 2);
      }

      CRGB color = ColorFromPalette( currentPalette, index, bri);
      leds = color;
    }
}

ihue+=1;
}

void loop() {
// Periodically choose a new palette, speed, and scale
ChangePaletteAndSettingsPeriodically();

// generate noise data
fillnoise8();

// convert the noise data to colors in the LED array
// using the current palette
mapNoiseToLEDsUsingPalette();

FastLED.show();
// delay(10);
}

#define HOLD_PALETTES_X_TIMES_AS_LONG 1

void ChangePaletteAndSettingsPeriodically()
{
uint8_t secondHand = ((millis() / 1000) / HOLD_PALETTES_X_TIMES_AS_LONG) % 60;
static uint8_t lastSecond = 99;

if( lastSecond != secondHand) {
    lastSecond = secondHand;
    if( secondHand ==0){ currentPalette = RainbowColors_p;         speed = 20; scale = 30; colorLoop = 1; }
    if( secondHand ==5){ SetupPurpleAndGreenPalette();             speed = 10; scale = 50; colorLoop = 1; }
    if( secondHand == 10){ SetupBlackAndWhiteStripedPalette();       speed = 20; scale = 30; colorLoop = 1; }
    if( secondHand == 15){ currentPalette = ForestColors_p;          speed =8; scale =120; colorLoop = 0; }
    if( secondHand == 20){ currentPalette = CloudColors_p;         speed =4; scale = 30; colorLoop = 0; }
    if( secondHand == 25){ currentPalette = LavaColors_p;            speed =8; scale = 50; colorLoop = 0; }
    if( secondHand == 30){ currentPalette = OceanColors_p;         speed = 20; scale = 90; colorLoop = 0; }
    if( secondHand == 35){ currentPalette = PartyColors_p;         speed = 20; scale = 30; colorLoop = 1; }
    if( secondHand == 40){ SetupRandomPalette();                     speed = 20; scale = 20; colorLoop = 1; }
    if( secondHand == 45){ SetupRandomPalette();                     speed = 50; scale = 50; colorLoop = 1; }
    if( secondHand == 50){ SetupRandomPalette();                     speed = 90; scale = 90; colorLoop = 1; }
    if( secondHand == 55){ currentPalette = RainbowStripeColors_p;   speed = 30; scale = 20; colorLoop = 1; }
}
}

// This function generates a random palette that's a gradient
// between four different colors.The first is a dim hue, the second is
// a bright hue, the third is a bright pastel, and the last is
// another bright hue.This gives some visual bright/dark variation
// which is more interesting than just a gradient of different hues.
void SetupRandomPalette()
{
currentPalette = CRGBPalette16(
                      CHSV( random8(), 255, 32),
                      CHSV( random8(), 255, 255),
                      CHSV( random8(), 128, 255),
                      CHSV( random8(), 255, 255));
}

// This function sets up a palette of black and white stripes,
// using code.Since the palette is effectively an array of
// sixteen CRGB colors, the various fill_* functions can be used
// to set them up.
void SetupBlackAndWhiteStripedPalette()
{
// 'black out' all 16 palette entries...
fill_solid( currentPalette, 16, CRGB::Black);
// and set every fourth one to white.
currentPalette = CRGB::White;
currentPalette = CRGB::White;
currentPalette = CRGB::White;
currentPalette = CRGB::White;

}

// This function sets up a palette of purple and green stripes.
void SetupPurpleAndGreenPalette()
{
CRGB purple = CHSV( HUE_PURPLE, 255, 255);
CRGB green= CHSV( HUE_GREEN, 255, 255);
CRGB black= CRGB::Black;

currentPalette = CRGBPalette16(
    green,green,black,black,
    purple, purple, black,black,
    green,green,black,black,
    purple, purple, black,black );
}


//
// Mark's xy coordinate mapping code.See the XYMatrix for more information on it.
//
uint16_t XY( uint8_t x, uint8_t y)
{
uint16_t i;
if( kMatrixSerpentineLayout == false) {
    i = (y * kMatrixWidth) + x;
}
if( kMatrixSerpentineLayout == true) {
    if( y & 0x01) {
      // Odd rows run backwards
      uint8_t reverseX = (kMatrixWidth - 1) - x;
      i = (y * kMatrixWidth) + reverseX;
    } else {
      // Even rows run forwards
      i = (y * kMatrixWidth) + x;
    }
}
return i;
}

驴友花雕 发表于 2022-7-14 15:22:39

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

每米60灯黑底裸板


驴友花雕 发表于 2022-7-14 15:52:57

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

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


驴友花雕 发表于 2022-7-14 15:59:20




驴友花雕 发表于 2022-7-14 16:00:53




驴友花雕 发表于 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异形屏,各种电子产品,电器设备跑马灯等。



驴友花雕 发表于 2022-7-14 16:23:36




驴友花雕 发表于 2022-7-14 16:25:07


驴友花雕 发表于 2022-7-14 16:26:16



驴友花雕 发表于 2022-7-14 17:10:10

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




驴友花雕 发表于 2022-7-14 17:14:55

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


驴友花雕 发表于 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 电源。



驴友花雕 发表于 2022-7-14 18:05:31

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


驴友花雕 发表于 2022-7-14 18:32:30

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

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

#include <FastLED.h>

#define NUM_LEDS 24
#define DATA_PIN 6
CRGB leds;
#define BRIGHTNESS33

void setup() {
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
leds = CRGB::Red;
FastLED.show();
delay(500);
leds = CRGB::Black;
FastLED.show();
delay(500);
}

驴友花雕 发表于 2022-7-14 18:39:31

实验场景图动态图


驴友花雕 发表于 2022-7-14 18:57:20

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

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

#include <FastLED.h>
#define DATA_PIN    6
#define NUM_LEDS    24
#define BRIGHTNESS33
#define LED_TYPE    WS2812B
#define COLOR_ORDER GRB
CRGB leds;
#define UPDATES_PER_SECOND 100

void setup() {
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
}

void loop() {
leds = CRGB::Red;
leds = CRGB::Green;
leds = CRGB::Blue;
FastLED.show();
delay(10);
}

驴友花雕 发表于 2022-7-14 19:01:43

实验场景图


驴友花雕 发表于 2022-7-14 19:13:34

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

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

#include <FastLED.h>
#define NUM_LEDS 24
#define DATA_PIN 6
CRGB leds;

void setup() {
FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
FastLED.setBrightness(33);
}

void fadeall() {
for (int i = 0; i < NUM_LEDS; i++) {
    leds.nscale8(250);
}
}

void loop() {
static uint8_t hue = 0;
for (int i = 0; i < NUM_LEDS; i++) {
    leds = CHSV(hue++, 255, 255);
    FastLED.show();
    fadeall();
    delay(10);
}

for (int i = (NUM_LEDS) - 1; i >= 0; i--) {
    leds = CHSV(hue++, 255, 255);
    FastLED.show();
    fadeall();
    delay(10);
}
}

驴友花雕 发表于 2022-7-14 19:20:29

实验场景图动态图


驴友花雕 发表于 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;将创建一个名为 LEDs 的数组,该数组可以保存所需 LED 数量的 RGB 数据。
现在在设置部分,我们将设置我们的 LED 灯条。
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:分别从红色、绿色和蓝色分量中设置颜色

leds.red =    50;
leds.green = 100;
leds.blue =150;

// ...or, using the shorter synonyms "r", "g", and "b"...
leds.r = 50;
leds.g = 100;
leds.b = 150;


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

leds = CRGB( 50, 100, 150);

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

leds = 0xFF007F;

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

leds = CRGB::HotPink;

示例 5:通过 setRGB 设置颜色

leds.setRGB( 50, 100, 150);

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

leds = leds;

页: [1] 2 3 4
查看完整版本: 【Arduino】168种传感器模块系列实验(216)---WS2812B幻彩LED灯带