驴友花雕 发表于 2022-10-21 18:00:19

【Arduino】168种传感器系列实验(214)---8x32位全彩WS2812B屏

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

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 可编程硬屏模块



驴友花雕 发表于 2022-10-23 15:52:54

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序十七:使用Adafruit_NeoPixel库的串口控制20种效果

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序十七:使用Adafruit_NeoPixel库的串口控制20种效果
*/

#include <Adafruit_NeoPixel.h>
#define PIN 6 //LED'in Din pinini yazın
#define NUM_LEDS 256 //Kaç tane LED'iniz varsa buraya yazın
#define BRIGHTNESS 20

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);
int mod;
int lastmod;
String veri;
int randommod;
int parlaklik = 0;

void setup() {
Serial.begin(9600);
veri.reserve(5);
strip.begin();
strip.show();
strip.setBrightness(BRIGHTNESS); //亮度范围0-255
Serial.println("WS2812准备就绪");
Serial.println("串口输入1-21");
}

void loop() {
switch (mod) {
    case 1:
      Serial.println("RGBLoop");
      RGBLoop();
      break;
    case 2:
      Serial.println("Strobe");
      Strobe(0xff, 0xff, 0xff, 10, 50, 1000);
      break;
    case 3:
      Serial.println("HalloweenEyes");
      HalloweenEyes(0xff, 0x00, 0x00, 1, 4, true, random(5, 50), random(10, 50), random(50, 300));
      break;
    case 4:
      Serial.println("NewKITT RightToLeft");
      NewKITT(0xff, 0, 0, 8, 10, 50);
      break;
    case 5:
      Serial.println("Twinkle");
      Twinkle(0xff, 0, 0, 10, 100, false);
      break;
    case 6:
      Serial.println("TwinkleRandom");
      Twinkle(0xff, 0, 0, 10, 100, false);
      break;
    case 7:
      Serial.println("Sparkle");
      Sparkle(0xff, 0xff, 0xff, 0);
      break;
    case 8:
      Serial.println("SnowSparkle");
      SnowSparkle(0x10, 0x10, 0x10, 20, random(100, 1000));
      break;
    case 9:
      Serial.println("RunningLights");
      RunningLights(0xff, 0xff, 0x00, 50);
      break;
    case 10:
      Serial.println("colorWipe");
      colorWipe(0x00, 0xff, 0x00, 50);
      colorWipe(0xff, 0x00, 0x00, 50);
      break;
    case 11:
      Serial.println("rainbowCycle");
      rainbowCycle(20);
      break;
    case 12:
      Serial.println("theaterChase");
      theaterChase(0xff, 0, 0, 50);
      break;
    case 13:
      Serial.println("theaterChaseRainbow");
      theaterChaseRainbow(50);
      break;
    case 14:
      Serial.println("Fire");
      Fire(55, 120, 15);
      break;
    case 15:
      Serial.println("BouncingBalls");
      meteorRain(0xff, 0xff, 0xff, 10, 64, true, 30);
      break;
    case 16:
      Serial.println("meteorRain");
      meteorRain(0xff, 0xff, 0xff, 10, 64, true, 30);
      break;
    case 17:
      Serial.println("Red");
      setAll(255, 0, 0);
      break;
    case 18:
      Serial.println("Green");
      setAll(0, 255, 0);
      break;
    case 19:
      Serial.println("Blue");
      setAll(0, 0, 255);
      break;
    case 20:
      Serial.println("ON");
      randommod = random(1, 19);
      switch (randommod) {
      case 1:
          Serial.println("RGBLoop");
          RGBLoop();
          break;
      case 2:
          Serial.println("Strobe");
          Strobe(0xff, 0xff, 0xff, 10, 50, 1000);
          break;
      case 3:
          Serial.println("HalloweenEyes");
          HalloweenEyes(0xff, 0x00, 0x00, 1, 4, true, random(5, 50), random(10, 50), random(50, 300));
          break;
      case 4:
          Serial.println("NewKITT RightToLeft");
          NewKITT(0xff, 0, 0, 8, 10, 50);
          break;
      case 5:
          Serial.println("Twinkle");
          Twinkle(0xff, 0, 0, 10, 100, false);
          break;
      case 6:
          Serial.println("TwinkleRandom");
          Twinkle(0xff, 0, 0, 10, 100, false);
          break;
      case 7:
          Serial.println("Sparkle");
          Sparkle(0xff, 0xff, 0xff, 0);
          break;
      case 8:
          Serial.println("SnowSparkle");
          SnowSparkle(0x10, 0x10, 0x10, 20, random(100, 1000));
          break;
      case 9:
          Serial.println("RunningLights");
          RunningLights(0xff, 0xff, 0x00, 50);
          break;
      case 10:
          Serial.println("colorWipe");
          colorWipe(0x00, 0xff, 0x00, 50);
          colorWipe(0xff, 0x00, 0x00, 50);
          break;
      case 11:
          Serial.println("rainbowCycle");
          rainbowCycle(20);
          break;
      case 12:
          Serial.println("theaterChase");
          theaterChase(0xff, 0, 0, 50);
          break;
      case 13:
          Serial.println("theaterChaseRainbow");
          theaterChaseRainbow(50);
          break;
      case 14:
          Serial.println("Fire");
          Fire(55, 120, 15);
          break;
      case 15:
          Serial.println("BouncingBalls");
          meteorRain(0xff, 0xff, 0xff, 10, 64, true, 30);
          break;
      case 16:
          Serial.println("meteorRain");
          meteorRain(0xff, 0xff, 0xff, 10, 64, true, 30);
          break;
      case 17:
          Serial.println("Red");
          setAll(255, 0, 0);
          break;
      case 18:
          Serial.println("Green");
          setAll(0, 255, 0);
          break;
      case 19:
          Serial.println("Blue");
          setAll(0, 0, 255);
          break;
      }
      break;
    case 21:
      Serial.println("OFF");
      setAll(0, 0, 0);
      break;
    default:
      //Serial.println("Red");
      setAll(255, 0, 0);
      break;
}
}
void meteorRain(byte red, byte green, byte blue, byte meteorSize, byte meteorTrailDecay, boolean meteorRandomDecay, int SpeedDelay) {
setAll(0, 0, 0);

for (int i = 0; i < NUM_LEDS + NUM_LEDS; i++) {


    // fade brightness all LEDs one step
    for (int j = 0; j < NUM_LEDS; j++) {
      if ( (!meteorRandomDecay) || (random(10) > 5) ) {
      fadeToBlack(j, meteorTrailDecay );
      }
      if (serialEvent() != false) break;
    }

    // draw meteor
    for (int j = 0; j < meteorSize; j++) {
      if ( ( i - j < NUM_LEDS) && (i - j >= 0) ) {
      setPixel(i - j, red, green, blue);
      }
      if (serialEvent() != false) break;
    }

    showStrip();
    delay(SpeedDelay);
    if (serialEvent() != false) break;
}
}

void fadeToBlack(int ledNo, byte fadeValue) {
#ifdef ADAFRUIT_NEOPIXEL_H
// NeoPixel
uint32_t oldColor;
uint8_t r, g, b;
int value;

oldColor = strip.getPixelColor(ledNo);
r = (oldColor & 0x00ff0000UL) >> 16;
g = (oldColor & 0x0000ff00UL) >> 8;
b = (oldColor & 0x000000ffUL);

r = (r <= 10) ? 0 : (int) r - (r * fadeValue / 256);
g = (g <= 10) ? 0 : (int) g - (g * fadeValue / 256);
b = (b <= 10) ? 0 : (int) b - (b * fadeValue / 256);

strip.setPixelColor(ledNo, r, g, b);
#endif
#ifndef ADAFRUIT_NEOPIXEL_H
// FastLED
leds.fadeToBlackBy( fadeValue );
#endif
}
void BouncingBalls(byte red, byte green, byte blue, int BallCount) {
float Gravity = -9.81;
int StartHeight = 1;

float Height;
float ImpactVelocityStart = sqrt( -2 * Gravity * StartHeight );
float ImpactVelocity;
float TimeSinceLastBounce;
int   Position;
longClockTimeSinceLastBounce;
float Dampening;

for (int i = 0 ; i < BallCount ; i++) {
    ClockTimeSinceLastBounce = millis();
    Height = StartHeight;
    Position = 0;
    ImpactVelocity = ImpactVelocityStart;
    TimeSinceLastBounce = 0;
    Dampening = 0.90 - float(i) / pow(BallCount, 2);
    if (serialEvent() != false) break;
}

while (true) {
    for (int i = 0 ; i < BallCount ; i++) {
      TimeSinceLastBounce =millis() - ClockTimeSinceLastBounce;
      Height = 0.5 * Gravity * pow( TimeSinceLastBounce / 1000 , 2.0 ) + ImpactVelocity * TimeSinceLastBounce / 1000;

      if ( Height < 0 ) {
      Height = 0;
      ImpactVelocity = Dampening * ImpactVelocity;
      ClockTimeSinceLastBounce = millis();

      if ( ImpactVelocity < 0.01 ) {
          ImpactVelocity = ImpactVelocityStart;
      }
      }
      Position = round( Height * (NUM_LEDS - 1) / StartHeight);
      if (serialEvent() != false) break;
    }

    for (int i = 0 ; i < BallCount ; i++) {
      setPixel(Position, red, green, blue);
      if (serialEvent() != false) break;
    }

    showStrip();
    setAll(0, 0, 0);
    if (serialEvent() != false) break;
}
}
void Fire(int Cooling, int Sparking, int SpeedDelay) {
static byte heat;
int cooldown;
for ( int i = 0; i < NUM_LEDS; i++) {
    cooldown = random(0, ((Cooling * 10) / NUM_LEDS) + 2);

    if (cooldown > heat) {
      heat = 0;
    } else {
      heat = heat - cooldown;
    }
    if (serialEvent() != false) break;
}
for ( int k = NUM_LEDS - 1; k >= 2; k--) {
    heat = (heat + heat + heat) / 3;
    if (serialEvent() != false) break;
}
if ( random(255) < Sparking ) {
    int y = random(7);
    heat = heat + random(160, 255);
}

for ( int j = 0; j < NUM_LEDS; j++) {
    setPixelHeatColor(j, heat );
    if (serialEvent() != false) break;
}

showStrip();
delay(SpeedDelay);
}

void setPixelHeatColor (int Pixel, byte temperature) {
byte t192 = round((temperature / 255.0) * 191);

byte heatramp = t192 & 0x3F; // 0..63
heatramp <<= 2; // scale up to 0..252
if ( t192 > 0x80) {                  // hottest
    setPixel(Pixel, 255, 255, heatramp);
} else if ( t192 > 0x40 ) {            // middle
    setPixel(Pixel, 255, heatramp, 0);
} else {                               // coolest
    setPixel(Pixel, heatramp, 0, 0);
}
}
void theaterChaseRainbow(int SpeedDelay) {
byte *c;

for (int j = 0; j < 256; j++) {
    for (int q = 0; q < 3; q++) {
      for (int i = 0; i < NUM_LEDS; i = i + 3) {
      c = Wheel( (i + j) % 255);
      setPixel(i + q, *c, *(c + 1), *(c + 2));
      if (serialEvent() != false) break;
      }
      showStrip();

      delay(SpeedDelay);

      for (int i = 0; i < NUM_LEDS; i = i + 3) {
      setPixel(i + q, 0, 0, 0);
      if (serialEvent() != false) break;
      }
      if (serialEvent() != false) break;
    }
    if (serialEvent() != false) break;
}
}
void theaterChase(byte red, byte green, byte blue, int SpeedDelay) {
for (int j = 0; j < 10; j++) {
    for (int q = 0; q < 3; q++) {
      for (int i = 0; i < NUM_LEDS; i = i + 3) {
      setPixel(i + q, red, green, blue);
      if (serialEvent() != false) break;
      }
      showStrip();

      delay(SpeedDelay);

      for (int i = 0; i < NUM_LEDS; i = i + 3) {
      setPixel(i + q, 0, 0, 0);
      if (serialEvent() != false) break;
      }
      if (serialEvent() != false) break;
    }
    if (serialEvent() != false) break;
}
}
void rainbowCycle(int SpeedDelay) {
byte *c;
uint16_t i, j;

for (j = 0; j < 256 * 5; j++) {
    for (i = 0; i < NUM_LEDS; i++) {
      c = Wheel(((i * 256 / NUM_LEDS) + j) & 255);
      setPixel(i, *c, *(c + 1), *(c + 2));
      if (serialEvent() != false) break;
    }
    showStrip();
    delay(SpeedDelay);
    if (serialEvent() != false) break;
}
}

byte * Wheel(byte WheelPos) {
static byte c;

if (WheelPos < 85) {
    c = WheelPos * 3;
    c = 255 - WheelPos * 3;
    c = 0;
} else if (WheelPos < 170) {
    WheelPos -= 85;
    c = 255 - WheelPos * 3;
    c = 0;
    c = WheelPos * 3;
} else {
    WheelPos -= 170;
    c = 0;
    c = WheelPos * 3;
    c = 255 - WheelPos * 3;
}

return c;
}
void colorWipe(byte red, byte green, byte blue, int SpeedDelay) {
for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
    showStrip();
    delay(SpeedDelay);
    if (serialEvent() != false) break;
}
}
void RunningLights(byte red, byte green, byte blue, int WaveDelay) {
int Position = 0;

for (int j = 0; j < NUM_LEDS * 2; j++)
{
    Position++; // = 0; //Position + Rate;
    for (int i = 0; i < NUM_LEDS; i++) {
      // sine wave, 3 offset waves make a rainbow!
      //float level = sin(i+Position) * 127 + 128;
      //setPixel(i,level,0,0);
      //float level = sin(i+Position) * 127 + 128;
      setPixel(i, ((sin(i + Position) * 127 + 128) / 255)*red,
               ((sin(i + Position) * 127 + 128) / 255)*green,
               ((sin(i + Position) * 127 + 128) / 255)*blue);
      if (serialEvent() != false) break;
    }

    showStrip();
    delay(WaveDelay);
    if (serialEvent() != false) break;
}
}
void SnowSparkle(byte red, byte green, byte blue, int SparkleDelay, int SpeedDelay) {
setAll(red, green, blue);
int Pixel = random(NUM_LEDS);
setPixel(Pixel, 0xff, 0xff, 0xff);
showStrip();
delay(SparkleDelay);
setPixel(Pixel, red, green, blue);
showStrip();
delay(SpeedDelay);
}
void Sparkle(byte red, byte green, byte blue, int SpeedDelay) {
int Pixel = random(NUM_LEDS);
setPixel(Pixel, red, green, blue);
showStrip();
delay(SpeedDelay);
setPixel(Pixel, 0, 0, 0);
}
void TwinkleRandom(int Count, int SpeedDelay, boolean OnlyOne) {
setAll(0, 0, 0);

for (int i = 0; i < Count; i++) {
    setPixel(random(NUM_LEDS), random(0, 255), random(0, 255), random(0, 255));
    showStrip();
    delay(SpeedDelay);
    if (OnlyOne) {
      setAll(0, 0, 0);
    }
    if (serialEvent() != false) break;
}

delay(SpeedDelay);
}
void Twinkle(byte red, byte green, byte blue, int Count, int SpeedDelay, boolean OnlyOne) {
setAll(0, 0, 0);

for (int i = 0; i < Count; i++) {
    setPixel(random(NUM_LEDS), red, green, blue);
    showStrip();
    delay(SpeedDelay);
    if (OnlyOne) {
      setAll(0, 0, 0);
    }
    if (serialEvent() != false) break;
}

delay(SpeedDelay);
}
void NewKITT(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
RightToLeft(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
LeftToRight(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
/*OutsideToCenter(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
    CenterToOutside(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
    LeftToRight(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
    RightToLeft(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
    OutsideToCenter(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);
    CenterToOutside(red, green, blue, EyeSize, SpeedDelay, ReturnDelay);*/
}

void CenterToOutside(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
for (int i = ((NUM_LEDS - EyeSize) / 2); i >= 0; i--) {
    setAll(0, 0, 0);

    setPixel(i, red / 10, green / 10, blue / 10);
    for (int j = 1; j <= EyeSize; j++) {
      setPixel(i + j, red, green, blue);
      if (serialEvent() != false) break;
    }
    setPixel(i + EyeSize + 1, red / 10, green / 10, blue / 10);

    setPixel(NUM_LEDS - i, red / 10, green / 10, blue / 10);
    for (int j = 1; j <= EyeSize; j++) {
      setPixel(NUM_LEDS - i - j, red, green, blue);
      if (serialEvent() != false) break;
    }
    setPixel(NUM_LEDS - i - EyeSize - 1, red / 10, green / 10, blue / 10);

    showStrip();
    delay(SpeedDelay);
    if (serialEvent() != false) break;
}
delay(ReturnDelay);
}

void OutsideToCenter(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
for (int i = 0; i <= ((NUM_LEDS - EyeSize) / 2); i++) {
    setAll(0, 0, 0);

    setPixel(i, red / 10, green / 10, blue / 10);
    for (int j = 1; j <= EyeSize; j++) {
      setPixel(i + j, red, green, blue);
      if (serialEvent() != false) break;
    }
    setPixel(i + EyeSize + 1, red / 10, green / 10, blue / 10);

    setPixel(NUM_LEDS - i, red / 10, green / 10, blue / 10);
    for (int j = 1; j <= EyeSize; j++) {
      setPixel(NUM_LEDS - i - j, red, green, blue);
      if (serialEvent() != false) break;
    }
    setPixel(NUM_LEDS - i - EyeSize - 1, red / 10, green / 10, blue / 10);

    showStrip();
    delay(SpeedDelay);
    if (serialEvent() != false) break;
}
delay(ReturnDelay);
}

void LeftToRight(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
for (int i = 0; i < NUM_LEDS - EyeSize - 2; i++) {
    setAll(0, 0, 0);
    setPixel(i, red / 10, green / 10, blue / 10);
    for (int j = 1; j <= EyeSize; j++) {
      setPixel(i + j, red, green, blue);
      if (serialEvent() != false) break;;
    }
    setPixel(i + EyeSize + 1, red / 10, green / 10, blue / 10);
    showStrip();
    delay(SpeedDelay);
    if (serialEvent() != false) break;
}
delay(ReturnDelay);
}

void RightToLeft(byte red, byte green, byte blue, int EyeSize, int SpeedDelay, int ReturnDelay) {
for (int i = NUM_LEDS - EyeSize - 2; i > 0; i--) {
    setAll(0, 0, 0);
    setPixel(i, red / 10, green / 10, blue / 10);
    for (int j = 1; j <= EyeSize; j++) {
      setPixel(i + j, red, green, blue);
      if (serialEvent() != false) break;
    }
    setPixel(i + EyeSize + 1, red / 10, green / 10, blue / 10);
    showStrip();
    delay(SpeedDelay);
    if (serialEvent() != false) break;
}
delay(ReturnDelay);
}
void HalloweenEyes(byte red, byte green, byte blue, int EyeWidth, int EyeSpace, boolean Fade, int Steps, int FadeDelay, int EndPause) {
randomSeed(analogRead(0));

int i;
int StartPoint= random( 0, NUM_LEDS - (2 * EyeWidth) - EyeSpace );
int Start2ndEye = StartPoint + EyeWidth + EyeSpace;

for (i = 0; i < EyeWidth; i++) {
    setPixel(StartPoint + i, red, green, blue);
    setPixel(Start2ndEye + i, red, green, blue);
    if (serialEvent() != false) break;
}

showStrip();

if (Fade == true) {
    float r, g, b;

    for (int j = Steps; j >= 0; j--) {
      r = j * (red / Steps);
      g = j * (green / Steps);
      b = j * (blue / Steps);

      for (i = 0; i < EyeWidth; i++) {
      setPixel(StartPoint + i, r, g, b);
      setPixel(Start2ndEye + i, r, g, b);
      if (serialEvent() != false) break;
      }

      showStrip();
      delay(FadeDelay);
      if (serialEvent() != false) break;
    }
}

setAll(0, 0, 0); // Set all black

delay(EndPause);
}
void Strobe(byte red, byte green, byte blue, int StrobeCount, int FlashDelay, int EndPause) {
for (int j = 0; j < StrobeCount; j++) {
    setAll(red, green, blue);
    showStrip();
    delay(FlashDelay);
    setAll(0, 0, 0);
    showStrip();
    delay(FlashDelay);
    if (serialEvent() != false) break;
}

delay(EndPause);
}
void RGBLoop() {
for (int j = 0; j < 3; j++ ) {
    // Fade IN
    for (int k = 0; k < 256; k++) {
      switch (j) {
      case 0: setAll(k, 0, 0); if (serialEvent() != false) break; break;
      case 1: setAll(0, k, 0); if (serialEvent() != false) break; break;
      case 2: setAll(0, 0, k); if (serialEvent() != false) break; break;
      }
      showStrip();
      if (serialEvent() != false)break;
    }
    // Fade OUT
    for (int k = 255; k >= 0; k--) {
      switch (j) {
      case 0: setAll(k, 0, 0); if (serialEvent() != false) break; break;
      case 1: setAll(0, k, 0); if (serialEvent() != false) break; break;
      case 2: setAll(0, 0, k); if (serialEvent() != false) break; break;
      }
      showStrip();
      if (serialEvent() != false)break;
    }
    if (serialEvent() != false)break;
}
}
void showStrip() {
#ifdef ADAFRUIT_NEOPIXEL_H
// NeoPixel
strip.show();
#endif
#ifndef ADAFRUIT_NEOPIXEL_H
// FastLED
FastLED.show();
#endif
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
#ifdef ADAFRUIT_NEOPIXEL_H
// NeoPixel
strip.setPixelColor(Pixel, strip.Color(red, green, blue));
#endif
#ifndef ADAFRUIT_NEOPIXEL_H
// FastLED
leds.r = red;
leds.g = green;
leds.b = blue;
#endif
}

void setAll(byte red, byte green, byte blue) {
for (int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
}
showStrip();
}
bool serialEvent() {
if (Serial.available()) {
    veri = Serial.readString();
    if (veri.charAt(0) == 'b') {
      veri = veri.substring(1, 4);
      parlaklik = veri.toInt();
      parlaklik = map(parlaklik, 0, 100, 0, 255);
      strip.setBrightness(parlaklik);
    }
    else {
      mod = veri.toInt();
      return true;
    }
}
return false;
}

驴友花雕 发表于 2022-10-23 11:43:04

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序十二:TwinkleFOX-淡入淡出的闪烁“假日”灯

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序十二:TwinkleFOX-淡入淡出的闪烁“假日”灯
*/

#include "FastLED.h"

#define NUM_LEDS      256
#define LED_TYPE   WS2811
#define COLOR_ORDER   GRB
#define DATA_PIN      6
//#define CLK_PIN       4
#define VOLTS          12
#define MAX_MA       4000

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

CRGBArray<NUM_LEDS> leds;

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

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

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

// 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);
FastLED.setBrightness(23);
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-10-23 14:31:41

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序十四:将噪声数据转换为 LED 阵列中的动态颜色

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序十四:将噪声数据转换为 LED 阵列中的动态颜色
*/

#include <FastLED.h>

#define LED_PIN   6
#define BRIGHTNESS26
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB

// Params for width and height
const uint8_t kMatrixWidth= 8;
const uint8_t kMatrixHeight = 32;

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


// This example combines two features of FastLED to produce a remarkable range of
// effects from a relatively small amount of code.This example combines FastLED's
// color palette lookup functions with FastLED's Perlin noise generator, and
// the combination is extremely powerful.
//
// You might want to look at the "ColorPalette" and "Noise" examples separately
// if this example code seems daunting.
//
//
// The basic setup here is that for each frame, we generate a new array of
// 'noise' data, and then map it onto the LED matrix through a color palette.
//
// Periodically, the color palette is changed, and new noise-generation parameters
// are chosen at the same time.In this example, specific noise-generation
// values have been selected to match the given color palettes; some are faster,
// or slower, or larger, or smaller than others, but there's no reason these
// parameters can't be freely mixed-and-matched.
//
// In addition, this example includes some fast automatic 'data smoothing' at
// lower noise speeds to help produce smoother animations in those cases.
//
// The FastLED built-in color palettes (Forest, Clouds, Lava, Ocean, Party) are
// used, as well as some 'hand-defined' ones, and some proceedurally generated
// palettes.


#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);
}



// There are several different palettes of colors demonstrated here.
//
// FastLED provides several 'preset' palettes: RainbowColors_p, RainbowStripeColors_p,
// OceanColors_p, CloudColors_p, LavaColors_p, ForestColors_p, and PartyColors_p.
//
// Additionally, you can manually define your own color palettes, or you can write
// code that creates color palettes on the fly.

// 1 = 5 sec per palette
// 2 = 10 sec per palette
// etc
#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-10-21 18:05:13




WS2812B主要特点
智能反接保护,电源反接不会损坏IC。
IC控制电路与LED点光源公用一个电源。
控制电路与RGB芯片集成在一个5050封装的元器件中,构成一个完整的外控像素点。
内置信号整形电路,任何一个像素点收到信号后经过波形整形再输出,保证线路波形畸变不会累加。
内置上电复位和掉电复位电路。
每个像素点的三基色颜色可实现256级亮度显示,完成16777216种颜色的全真色彩显示,扫描频率不低于400Hz/s。
串行级联接口,能通过一根信号线完成数据的接收与解码。
任意两点传传输距离在不超过5米时无需增加任何电路。
当刷新速率30帧/秒时,级联数不小于1024点。
数据发送速度可达800Kbps。
光的颜色高度一致,性价比高。

主要应用领域
LED全彩发光字灯串,LED全彩模组, LED全彩软灯条硬灯条,LED护栏管。
LED点光源,LED像素屏,LED异形屏,各种电子产品,电器设备跑马灯。

驴友花雕 发表于 2022-10-21 18:10:27


驴友花雕 发表于 2022-10-21 18:14:53

WS2812B灯屏电原理参考图




驴友花雕 发表于 2022-10-21 18:30:19

实验涉及到的几个WS2812B相关库
安装FastLED库,工具—管理库—搜索FastLED—安装
安装NeoPixel库,工具—管理库—搜索NeoPixel—安装
安装Adafruit_NeoPixel库,
下载https://github.com/adafruit/Adafruit_NeoPixel





驴友花雕 发表于 2022-10-21 18:47:48


驴友花雕 发表于 2022-10-22 10:15:02

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之一:LED循环绿色快闪测试

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之一:LED循环绿色快闪测试
*/

#include <Adafruit_NeoPixel.h>

#define PIN 6
#define MAX_LED 255

#define ADD true
#define SUB false

int val = 0;
boolean stat = ADD;

Adafruit_NeoPixel strip = Adafruit_NeoPixel( MAX_LED, PIN, NEO_RGB + NEO_KHZ800 );

void setup() {
strip.begin();
strip.show();
}

void loop() {
uint8_t i, a = 0;
uint32_t color = strip.Color(255, 0, 0);
while (a < 256)
{
    for (i = 0; i < 255; i++)
    {
      if (i == a) strip.setPixelColor(i, color);
      else strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(2);
    a++;
}
}

驴友花雕 发表于 2022-10-22 10:21:49

实验场景图



驴友花雕 发表于 2022-10-22 10:34:00

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之二:全屏LED呼吸灯

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之二:全屏LED呼吸灯
*/

#include <FastLED.h>

#define LED_PIN   6   
#define NUM_LEDS    256   
CRGB leds;

void setup() {
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(20);
}

int h = 0;

void loop() {
for (int i = 0; i < NUM_LEDS; i++) {
    leds = CHSV( h, 255, 255);
    FastLED.show();
}
delay(1);
h = (h + 3) % 255;
}

驴友花雕 发表于 2022-10-22 10:35:46

实验场景图


驴友花雕 发表于 2022-10-22 11:44:57

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之三:简单的三色流水灯

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之三:简单的三色流水灯
*/

#include <FastLED.h>

#define LED_PIN    6
#define NUM_LEDS   256
CRGB leds;

void setup() {
FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(250);
}

void loop() {
for (int i = 0; i < NUM_LEDS; i++) {
    leds = CRGB::Red;
    FastLED.show();
    delay(1);
    leds = CRGB::Black;
}
    for (int i = NUM_LEDS; i > 0; i--) {
    leds = CRGB::Blue;
    FastLED.show();
    delay(1);
    leds = CRGB::Black;
}
    for (int i = 0; i < NUM_LEDS; i++) {
    leds = CRGB::Green;
    FastLED.show();
    delay(1);
    leds = CRGB::Black;
}
      for (int i = NUM_LEDS; i > 0; i--) {
    leds = CRGB::Blue;
    FastLED.show();
    delay(1);
    leds = CRGB::Black;
}
}

驴友花雕 发表于 2022-10-22 11:56:00

实验场景图动态图



驴友花雕 发表于 2022-10-22 13:47:02

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之四:循环快扫红绿蓝色LED满屏流水彩虹灯

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之四:循环快扫红绿蓝色LED满屏流水彩虹灯
*/

#include <Adafruit_NeoPixel.h>

#define PIN 6
#define BRIGHTNESS 256

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

void setup() {
strip.setBrightness(30);
strip.begin();
strip.show();
}

void loop() {
colorWipe(strip.Color(150, 0, 0), 50); // Red
colorWipe(strip.Color(0, 150, 0), 50); // Green
colorWipe(strip.Color(0, 0, 150), 50); // Blue
colorWipe(strip.Color(150, 150, 150), 50); // BlueWite
rainbowCycle(1);

}

void colorWipe(uint32_t c, uint8_t wait) {
for (uint16_t i = 0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(3);
}
}

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();
    delay(3);
}
}

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();
    delay(3);
}
}

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);
}
}

驴友花雕 发表于 2022-10-22 13:48:46

实验场景图动态图



驴友花雕 发表于 2022-10-22 13:50:59

实验场景图动态图2



驴友花雕 发表于 2022-10-22 15:03:37

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之五:255位循环流水变幻呼吸灯

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之五:255位循环流水变幻呼吸灯
*/

// NeoPixel test program showing use of the WHITE channel for RGBW
// pixels only (won't look correct on regular RGB NeoPixel strips).

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1:
#define LED_PIN   6

// How many NeoPixels are attached to the Arduino?
#define LED_COUNT255

// NeoPixel brightness, 0 (min) to 255 (max)
#define BRIGHTNESS 50

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRBW + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
//   NEO_KHZ800800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB   Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB   Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)

void setup() {
// These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
// Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.

strip.begin();         // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show();            // Turn OFF all pixels ASAP
strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
}

void loop() {
// Fill along the length of the strip in various colors...
colorWipe(strip.Color(255,   0,   0)   , 50); // Red
colorWipe(strip.Color(0, 255,   0)   , 50); // Green
colorWipe(strip.Color(0,   0, 255)   , 50); // Blue
colorWipe(strip.Color(0,   0,   0, 255), 50); // True white (not RGB white)

whiteOverRainbow(75, 5);

pulseWhite(5);

rainbowFade2White(3, 3, 1);
}

// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);         //Set pixel's color (in RAM)
    strip.show();                        //Update strip to match
    delay(4);                           //Pause for a moment
}
}

void whiteOverRainbow(int whiteSpeed, int whiteLength) {

if(whiteLength >= strip.numPixels()) whiteLength = strip.numPixels() - 1;

int      head          = whiteLength - 1;
int      tail          = 0;
int      loops         = 3;
int      loopNum       = 0;
uint32_t lastTime      = millis();
uint32_t firstPixelHue = 0;

for(;;) { // Repeat forever (or until a 'break' or 'return')
    for(int i=0; i<strip.numPixels(); i++) {// For each pixel in strip...
      if(((i >= tail) && (i <= head)) ||      //If between head & tail...
         ((tail > head) && ((i >= tail) || (i <= head)))) {
      strip.setPixelColor(i, strip.Color(0, 0, 0, 255)); // Set white
      } else {                                             // else set rainbow
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
      }
    }

    strip.show(); // Update strip with new contents
    // There's no delay here, it just runs full-tilt until the timer and
    // counter combination below runs out.

    firstPixelHue += 40; // Advance just a little along the color wheel

    if((millis() - lastTime) > whiteSpeed) { // Time to update head/tail?
      if(++head >= strip.numPixels()) {      // Advance head, wrap around
      head = 0;
      if(++loopNum >= loops) return;
      }
      if(++tail >= strip.numPixels()) {      // Advance tail, wrap around
      tail = 0;
      }
      lastTime = millis();                   // Save time of last movement
    }
}
}

void pulseWhite(uint8_t wait) {
for(int j=0; j<256; j++) { // Ramp up from 0 to 255
    // Fill entire strip with white at gamma-corrected brightness level 'j':
    strip.fill(strip.Color(0, 0, 0, strip.gamma8(j)));
    strip.show();
    delay(4);
}

for(int j=255; j>=0; j--) { // Ramp down from 255 to 0
    strip.fill(strip.Color(0, 0, 0, strip.gamma8(j)));
    strip.show();
    delay(4);
}
}

void rainbowFade2White(int wait, int rainbowLoops, int whiteLoops) {
int fadeVal=0, fadeMax=100;

// Hue of first pixel runs 'rainbowLoops' complete loops through the color
// wheel. Color wheel has a range of 65536 but it's OK if we roll over, so
// just count from 0 to rainbowLoops*65536, using steps of 256 so we
// advance around the wheel at a decent clip.
for(uint32_t firstPixelHue = 0; firstPixelHue < rainbowLoops*65536;
    firstPixelHue += 256) {

    for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...

      // Offset pixel hue by an amount to make one full revolution of the
      // color wheel (range of 65536) along the length of the strip
      // (strip.numPixels() steps):
      uint32_t pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());

      // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
      // optionally add saturation and value (brightness) (each 0 to 255).
      // Here we're using just the three-argument variant, though the
      // second value (saturation) is a constant 255.
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue, 255,
      255 * fadeVal / fadeMax)));
    }

    strip.show();
    delay(4);

    if(firstPixelHue < 65536) {                              // First loop,
      if(fadeVal < fadeMax) fadeVal++;                     // fade in
    } else if(firstPixelHue >= ((rainbowLoops-1) * 65536)) { // Last loop,
      if(fadeVal > 0) fadeVal--;                           // fade out
    } else {
      fadeVal = fadeMax; // Interim loop, make sure fade is at max
    }
}

for(int k=0; k<whiteLoops; k++) {
    for(int j=0; j<256; j++) { // Ramp up 0 to 255
      // Fill entire strip with white at gamma-corrected brightness level 'j':
      strip.fill(strip.Color(0, 0, 0, strip.gamma8(j)));
      strip.show();
    }
    delay(20); // Pause 1 second
    for(int j=255; j>=0; j--) { // Ramp down 255 to 0
      strip.fill(strip.Color(0, 0, 0, strip.gamma8(j)));
      strip.show();
    }
}

delay(10); // Pause 1/2 second
}

驴友花雕 发表于 2022-10-22 15:08:34

实验场景图



驴友花雕 发表于 2022-10-22 15:10:32

实验场景图 2



驴友花雕 发表于 2022-10-22 15:26:34

【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之六:多彩流水灯变幻彩虹灯

/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十四:WS2812B全彩RGB像素屏 8x32点阵LED显示屏 硬屏模块
项目程序之六:多彩流水灯变幻彩虹灯
*/

#include <Adafruit_NeoPixel.h>    //needed for the WS2812
#include <avr/pgmspace.h>         //needed for PROGMEM

#define PIN 6                  //Pin 1 is DATA In on the bottom Ring
#define BRIGHTNESS 255             // brightness reduced



//Lookup for the Candle light
const unsigned int candles[] PROGMEM =
{
15, 10, 48, 45, 36, 19, 59, 29, 5, 43, 41, 39, 24, 3, 61
};

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

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
pinMode(PIN, OUTPUT);
strip.begin();
strip.setBrightness(BRIGHTNESS); // set brightness
strip.show(); // Initialize all pixels to 'off'
}

void loop() {
tree();
delay(100);

colorcrazy();

theaterChaseRainbow(50);

comet();

warpdrive();
warpdrive();

rainbowCycle(1);

rainbow(5);
rainbow(5);
rainbow(5);


colorWipe(strip.Color(255, 0, 0), 50); // Red
colorWipe(strip.Color(0, 255, 0), 50); // Green
colorWipe(strip.Color(0, 0, 255), 50); // Blue

//
//
//cometr();
//Tree light:

//
//warpdrive();
//
//
//comet();


/*
    // Some example procedures showing how to display to the pixels:
    colorWipe(strip.Color(255, 0, 0), 50); // Red
    colorWipe(strip.Color(0, 255, 0), 50); // Green
    colorWipe(strip.Color(0, 0, 255), 50); // Blue
    // Send a theater pixel chase in...
    theaterChase(strip.Color(127, 127, 127), 50); // White
    theaterChase(strip.Color(127,   0,   0), 50); // Red
    theaterChase(strip.Color(0,   0, 127), 50); // Blue
    rainbow(20);
    rainbowCycle(20);
    theaterChaseRainbow(50);
*/
}

//Sub-----------------------------------------------------------------------

//Comet
void comet() {
for (uint16_t i = strip.numPixels(); i > 0; i--) {
    strip.setPixelColor(i, strip.Color(0, 0, 255));
    fadethemall(10);
    fadethemall(10);
}
}

void cometr() {
for (uint16_t i = strip.numPixels(); i > 0; i--) {
    strip.setPixelColor(i, strip.Color(255, 0, 0));
    fadethemall(10);
    fadethemall(10);
}
}


//From top down white pulses
void warpdrive() {

//Top Led
strip.setPixelColor(60, strip.Color(255, 255, 255));
strip.show();
//fade a bit
for (int i = 0; i < 20; i++)
{
    fadethemall(20);
}
//8 Ring
for (int i = 52; i < 60; i++)
{
    strip.setPixelColor(i, strip.Color(255, 255, 255));
}
strip.show();
//fade a bit
for (int i = 0; i < 20; i++)
{
    fadethemall(20);
}
//12 Ring
for (int i = 40; i < 52; i++)
{
    strip.setPixelColor(i, strip.Color(255, 255, 255));
}
strip.show();
//fade a bit
for (int i = 0; i < 20; i++)
{
    fadethemall(20);
}
//16 Ring
for (int i = 24; i < 40; i++)
{
    strip.setPixelColor(i, strip.Color(255, 255, 255));
}
strip.show();
//fade a bit
for (int i = 0; i < 20; i++)
{
    fadethemall(20);
}
//24 Ring
for (int i = 0; i < 24; i++)
{
    strip.setPixelColor(i, strip.Color(255, 255, 255));
}
strip.show();
//fade a bit
for (int i = 0; i < 20; i++)
{
    fadethemall(20);
}

//Extra by John Kerr
strip.setPixelColor(60, strip.Color(0, 0, 0));
strip.show();
//fade a bit
for (int i = 0; i < 20; i++)
{
    fadethemall(20);
}

}

//This reduces the brightness of all leds
void fadethemall(uint8_t wait) {
for (uint16_t i = 0; i < strip.numPixels(); i++) {
    uint32_t color = strip.getPixelColor(i);
    int r;
    int g;
    int b;
    r = (uint8_t)(color >> 16);
    g = (uint8_t)(color >>8);
    b = (uint8_t)color;

    if (r > 0)
    {
      r = r - 1;
    }
    else
    {
      r = 0;
    }

    if (g > 0)
    {
      g = g - 1;
    }
    else
    {
      g = 0;
    }

    if (b > 0)
    {
      b = b - 1;
    }
    else
    {
      b = 0;
    }

    strip.setPixelColor(i, strip.Color(r, g, b));
}
strip.show();
delay(20);
}

//This drives the WS2812 in a crazy pattern, fun!
void colorcrazy() {
colorWipe(strip.Color(255, 0, 0), 25); // Red
colorWipe(strip.Color(0, 255, 0), 25); // Green
colorWipe(strip.Color(0, 0, 255), 25); // Blue
theaterChaseRainbow(5);
}

//This lights up the tree in green, then add the white "candles"
void tree() {

colorWipe(strip.Color(0, 50, 0), 50); // Green

//light "candles"
//Show the S:
for (int i = 0; i < 16; i++)
{
    strip.setPixelColor(pgm_read_word(&candles) - 1, strip.Color(255, 255, 255));
    strip.show();
    delay(20);
}
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
for (uint16_t i = 0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(20);
}
}

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();
    delay(20);
}
}

// 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();
    delay(20);
}
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
for (int j = 0; j < 10; j++) { //do 10 cycles of chasing
    for (int q = 0; q < 3; q++) {
      for (int i = 0; i < strip.numPixels(); i = i + 3) {
      strip.setPixelColor(i + q, c);//turn every third pixel on
      }
      strip.show();

      delay(20);

      for (int i = 0; i < strip.numPixels(); i = i + 3) {
      strip.setPixelColor(i + q, 0);      //turn every third pixel off
      }
    }
}
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
for (int j = 0; j < 256; j++) {   // cycle all 256 colors in the wheel
    for (int q = 0; q < 3; q++) {
      for (int i = 0; i < strip.numPixels(); i = i + 3) {
      strip.setPixelColor(i + q, Wheel( (i + j) % 255)); //turn every third pixel on
      }
      strip.show();

      delay(20);

      for (int i = 0; i < strip.numPixels(); i = i + 3) {
      strip.setPixelColor(i + q, 0);      //turn every third pixel off
      }
    }
}
}

// 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) {
WheelPos = 255 - WheelPos;
if (WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
} else if (WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
} else {
    WheelPos -= 170;
    return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}
}

驴友花雕 发表于 2022-10-22 15:28:05

实验场景图



驴友花雕 发表于 2022-10-22 15:46:19

实验开源图形编程(Mind+、编玩边学)



页: [1] 2 3 4
查看完整版本: 【Arduino】168种传感器系列实验(214)---8x32位全彩WS2812B屏