驴友花雕
发表于 2022-7-17 10:49:18
实验场景图动态图
驴友花雕
发表于 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 13:16:40
实验场景图动态图
驴友花雕
发表于 2022-7-17 15:34:03
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序十五:动画,不断变化的彩虹
/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序十五:动画,不断变化的彩虹
*/
#include "FastLED.h"
#if FASTLED_VERSION < 3001000
#error "Requires FastLED 3.1 or later; check github for latest code."
#endif
#define DATA_PIN 6
//#define CLK_PIN 4
#define LED_TYPE WS2811
#define COLOR_ORDER GRB
#define NUM_LEDS 24
#define BRIGHTNESS33
CRGB leds;
void setup() {
delay(3000); // 3 second delay for recovery
// tell FastLED about the LED strip configuration
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
.setCorrection(TypicalLEDStrip)
.setDither(BRIGHTNESS < 255);
// set master brightness control
FastLED.setBrightness(BRIGHTNESS);
}
void loop(){
pride();
FastLED.show();
}
// This function draws rainbows with an ever-changing,
// widely-varying set of parameters.
void pride()
{
static uint16_t sPseudotime = 0;
static uint16_t sLastMillis = 0;
static uint16_t sHue16 = 0;
uint8_t sat8 = beatsin88( 87, 220, 250);
uint8_t brightdepth = beatsin88( 341, 96, 224);
uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
uint8_t msmultiplier = beatsin88(147, 23, 60);
uint16_t hue16 = sHue16;//gHue * 256;
uint16_t hueinc16 = beatsin88(113, 1, 3000);
uint16_t ms = millis();
uint16_t deltams = ms - sLastMillis ;
sLastMillis= ms;
sPseudotime += deltams * msmultiplier;
sHue16 += deltams * beatsin88( 400, 5,9);
uint16_t brightnesstheta16 = sPseudotime;
for( uint16_t i = 0 ; i < NUM_LEDS; i++) {
hue16 += hueinc16;
uint8_t hue8 = hue16 / 256;
brightnesstheta16+= brightnessthetainc16;
uint16_t b16 = sin16( brightnesstheta16) + 32768;
uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
bri8 += (255 - brightdepth);
CRGB newcolor = CHSV( hue8, sat8, bri8);
uint16_t pixelnumber = i;
pixelnumber = (NUM_LEDS-1) - pixelnumber;
nblend( leds, newcolor, 64);
}
}
驴友花雕
发表于 2022-7-17 15:53:33
实验场景图
驴友花雕
发表于 2022-7-17 16:04:38
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序十六:太平洋——温柔的蓝绿色海浪
/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序十六:太平洋——温柔的蓝绿色海浪
*/
#define FASTLED_ALLOW_INTERRUPTS 0
#include <FastLED.h>
FASTLED_USING_NAMESPACE
#define DATA_PIN 6
#define NUM_LEDS 24
#define MAX_POWER_MILLIAMPS 500
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB
//////////////////////////////////////////////////////////////////////////
CRGB leds;
void setup() {
delay( 3000); // 3 second delay for boot recovery, and a moment of silence
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
.setCorrection( TypicalLEDStrip );
FastLED.setMaxPowerInVoltsAndMilliamps( 5, MAX_POWER_MILLIAMPS);
}
void loop(){
EVERY_N_MILLISECONDS( 20) {
pacifica_loop();
FastLED.show();
}
}
//////////////////////////////////////////////////////////////////////////
//
// The code for this animation is more complicated than other examples, and
// while it is "ready to run", and documented in general, it is probably not
// the best starting point for learning.Nevertheless, it does illustrate some
// useful techniques.
//
//////////////////////////////////////////////////////////////////////////
//
// In this animation, there are four "layers" of waves of light.
//
// Each layer moves independently, and each is scaled separately.
//
// All four wave layers are added together on top of each other, and then
// another filter is applied that adds "whitecaps" of brightness where the
// waves line up with each other more.Finally, another pass is taken
// over the led array to 'deepen' (dim) the blues and greens.
//
// The speed and scale and motion each layer varies slowly within independent
// hand-chosen ranges, which is why the code has a lot of low-speed 'beatsin8' functions
// with a lot of oddly specific numeric ranges.
//
// These three custom blue-green color palettes were inspired by the colors found in
// the waters off the southern coast of California, https://goo.gl/maps/QQgd97jjHesHZVxQ7
//
CRGBPalette16 pacifica_palette_1 =
{ 0x000507, 0x000409, 0x00030B, 0x00030D, 0x000210, 0x000212, 0x000114, 0x000117,
0x000019, 0x00001C, 0x000026, 0x000031, 0x00003B, 0x000046, 0x14554B, 0x28AA50 };
CRGBPalette16 pacifica_palette_2 =
{ 0x000507, 0x000409, 0x00030B, 0x00030D, 0x000210, 0x000212, 0x000114, 0x000117,
0x000019, 0x00001C, 0x000026, 0x000031, 0x00003B, 0x000046, 0x0C5F52, 0x19BE5F };
CRGBPalette16 pacifica_palette_3 =
{ 0x000208, 0x00030E, 0x000514, 0x00061A, 0x000820, 0x000927, 0x000B2D, 0x000C33,
0x000E39, 0x001040, 0x001450, 0x001860, 0x001C70, 0x002080, 0x1040BF, 0x2060FF };
void pacifica_loop()
{
// Increment the four "color index start" counters, one for each wave layer.
// Each is incremented at a different speed, and the speeds vary over time.
static uint16_t sCIStart1, sCIStart2, sCIStart3, sCIStart4;
static uint32_t sLastms = 0;
uint32_t ms = GET_MILLIS();
uint32_t deltams = ms - sLastms;
sLastms = ms;
uint16_t speedfactor1 = beatsin16(3, 179, 269);
uint16_t speedfactor2 = beatsin16(4, 179, 269);
uint32_t deltams1 = (deltams * speedfactor1) / 256;
uint32_t deltams2 = (deltams * speedfactor2) / 256;
uint32_t deltams21 = (deltams1 + deltams2) / 2;
sCIStart1 += (deltams1 * beatsin88(1011,10,13));
sCIStart2 -= (deltams21 * beatsin88(777,8,11));
sCIStart3 -= (deltams1 * beatsin88(501,5,7));
sCIStart4 -= (deltams2 * beatsin88(257,4,6));
// Clear out the LED array to a dim background blue-green
fill_solid( leds, NUM_LEDS, CRGB( 2, 6, 10));
// Render each of four layers, with different scales and speeds, that vary over time
pacifica_one_layer( pacifica_palette_1, sCIStart1, beatsin16( 3, 11 * 256, 14 * 256), beatsin8( 10, 70, 130), 0-beat16( 301) );
pacifica_one_layer( pacifica_palette_2, sCIStart2, beatsin16( 4,6 * 256,9 * 256), beatsin8( 17, 40,80), beat16( 401) );
pacifica_one_layer( pacifica_palette_3, sCIStart3, 6 * 256, beatsin8( 9, 10,38), 0-beat16(503));
pacifica_one_layer( pacifica_palette_3, sCIStart4, 5 * 256, beatsin8( 8, 10,28), beat16(601));
// Add brighter 'whitecaps' where the waves lines up more
pacifica_add_whitecaps();
// Deepen the blues and greens a bit
pacifica_deepen_colors();
}
// Add one layer of waves into the led array
void pacifica_one_layer( CRGBPalette16& p, uint16_t cistart, uint16_t wavescale, uint8_t bri, uint16_t ioff)
{
uint16_t ci = cistart;
uint16_t waveangle = ioff;
uint16_t wavescale_half = (wavescale / 2) + 20;
for( uint16_t i = 0; i < NUM_LEDS; i++) {
waveangle += 250;
uint16_t s16 = sin16( waveangle ) + 32768;
uint16_t cs = scale16( s16 , wavescale_half ) + wavescale_half;
ci += cs;
uint16_t sindex16 = sin16( ci) + 32768;
uint8_t sindex8 = scale16( sindex16, 240);
CRGB c = ColorFromPalette( p, sindex8, bri, LINEARBLEND);
leds += c;
}
}
// Add extra 'white' to areas where the four layers of light have lined up brightly
void pacifica_add_whitecaps()
{
uint8_t basethreshold = beatsin8( 9, 55, 65);
uint8_t wave = beat8( 7 );
for( uint16_t i = 0; i < NUM_LEDS; i++) {
uint8_t threshold = scale8( sin8( wave), 20) + basethreshold;
wave += 7;
uint8_t l = leds.getAverageLight();
if( l > threshold) {
uint8_t overage = l - threshold;
uint8_t overage2 = qadd8( overage, overage);
leds += CRGB( overage, overage2, qadd8( overage2, overage2));
}
}
}
// Deepen the blues and greens
void pacifica_deepen_colors()
{
for( uint16_t i = 0; i < NUM_LEDS; i++) {
leds.blue = scale8( leds.blue,145);
leds.green= scale8( leds.green, 200);
leds |= CRGB( 2, 5, 7);
}
}
驴友花雕
发表于 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-17 17:07:51
实验的视频记录
https://v.youku.com/v_show/id_XNTg4NjQyMzE4OA==.html?spm=a2hcb.playlsit.page.1
https://v.youku.com/v_show/id_XNTg4NjQyMzE4OA==.html?spm=a2hcb.playlsit.page.1
驴友花雕
发表于 2022-7-17 17:09:19
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序十八:三速七彩风火轮
/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序十八:三速七彩风火轮
*/
#include <Adafruit_NeoPixel.h>
#define LED_PIN 6
#define LED_COUNT 24
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(30); // Set BRIGHTNESS to about 1/5 (max = 255)
}
void loop() {
theaterChaseTwo(strip.Color(127, 127, 127), 100);// set brightness to 100
theaterChaseTwo(strip.Color(255, 255, 0), 100);
theaterChaseTwo(strip.Color(127, 0, 0), 100);
theaterChaseTwo(strip.Color(0, 255, 0), 100);
theaterChaseTwo(strip.Color(0, 0, 127), 100);
theaterChaseTwo(strip.Color(143, 0, 255), 100);
theaterChase(strip.Color(127, 127, 127), 50); // 50 = half brightness
theaterChase(strip.Color(255, 255, 0), 50);
theaterChase(strip.Color(127, 0, 0), 50);
theaterChase(strip.Color(0, 255, 0), 50);
theaterChase(strip.Color(0, 0, 127), 50);
theaterChase(strip.Color(143, 0, 255), 50);
theaterChase(strip.Color(127, 127, 127), 25); // set brightness to 25
theaterChase(strip.Color(255, 255, 0), 25);
theaterChase(strip.Color(127, 0, 0), 25);
theaterChase(strip.Color(0, 255, 0), 25);
theaterChase(strip.Color(0, 0, 127), 25);
theaterChase(strip.Color(143, 0, 255), 25);
}
void theaterChase(uint32_t color, int wait) {
for(int a=0; a<10; a++) {
for(int b=0; b<3; b++) {
strip.clear();
for(int c=b; c<strip.numPixels(); c += 3) {
strip.setPixelColor(c, color);
}
strip.show();
delay(wait);
}
}}
void theaterChaseTwo(uint32_t color, int wait) {
for(int a=0; a<5; a++) {
for(int b=0; b<4; b++) {
strip.clear();
for(int c=b; c<strip.numPixels(); c += 3) {
strip.setPixelColor(c, color);
}
strip.show();
delay(wait);
}
}}
void theaterChaseThree(uint32_t color, int wait) {
for(int a=0; a<10; a++) {
for(int b=0; b<2; b++) {
strip.clear();
for(int c=b; c<strip.numPixels(); c += 3) {
strip.setPixelColor(c, color);
}
strip.show();
delay(wait);
}
}}
驴友花雕
发表于 2022-7-17 17:11:31
实验场景图
驴友花雕
发表于 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-18 09:31:21
实验场景图动态图
驴友花雕
发表于 2022-7-18 10:49:58
实验串口返回情况(可以监视不同模式的转换)
驴友花雕
发表于 2022-7-18 18:32:30
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序二十:外部声音触发(阙值可调整)动态节奏灯带
/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序二十:外部声音触发(阙值可调整)动态节奏灯带
*/
#include <WS2812FX.h>
#define LED_COUNT 24
#define LED_PIN 6
#define ANALOG_PIN A0
#define ANALOG_THRESHOLD 512
#define TIMER_MS 3000
WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_RGB + NEO_KHZ800);
unsigned long last_trigger = 0;
unsigned long now = 0;
void setup() {
ws2812fx.init();
ws2812fx.setBrightness(33);
ws2812fx.setMode(FX_MODE_RANDOM_COLOR);
}
void loop() {
now = millis();
ws2812fx.service();
if(now - last_trigger > TIMER_MS) {
ws2812fx.trigger();
last_trigger = now;
}
if(analogRead(ANALOG_PIN) > ANALOG_THRESHOLD) {
ws2812fx.trigger();
}
}
驴友花雕
发表于 2022-7-18 19:15:07
实验场景图动态图
驴友花雕
发表于 2022-7-18 19:18:06
实验的视频记录
https://v.youku.com/v_show/id_XNTg4NjY5MTk1Mg==.html?spm=a2hcb.playlsit.page.1
https://v.youku.com/v_show/id_XNTg4NjY5MTk1Mg==.html?spm=a2hcb.playlsit.page.1
驴友花雕
发表于 2022-7-20 15:26:30
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序二十一:MegunoLink音乐反应式24颗LED灯带
/*
【Arduino】168种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百一十六:WS2812B幻彩LED灯带 5V全彩灯条5050灯珠内置IC炫彩单点单控软灯条模块
实验程序二十一:MegunoLink音乐反应式24颗LED灯带
*/
#include<FastLED.h>
#include<MegunoLink.h>
#include<Filter.h>
// define necessary parameters
#define N_PIXELS24
#define MIC_PIN A0
#define LED_PIN D6 // labeled "D6" on the board
// the following parameters can be tweaked according to your audio levels
#define NOISE 50
#define TOP (N_PIXELS+2) // allow the max level to be slightly off scale
#define LED_TYPEWS2811
#define BRIGHTNESS18 // a little dim for recording purposes
#define COLOR_ORDER GRB
// declare the LED array
CRGB leds;
// define the variables needed for the audio levels
int lvl = 0, minLvl = 0, maxLvl = 600; // tweak the min and max as needed
// instantiate the filter class for smoothing the raw audio signal
ExponentialFilter<long> ADCFilter(5,0);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
// initialize the LED object
FastLED.addLeds<LED_TYPE,LED_PIN,COLOR_ORDER>(leds,N_PIXELS).setCorrection(TypicalLEDStrip);
FastLED.setBrightness(BRIGHTNESS);
}
void loop() {
// put your main code here, to run repeatedly:
// read the audio signal and filter it
int n, height;
n = analogRead(MIC_PIN);
// remove the MX9614 bias of 1.25VDC
n = abs(1023 - n);
// hard limit noise/hum
n = (n <= NOISE) ? 0 : abs(n - NOISE);
// apply the exponential filter to smooth the raw signal
ADCFilter.Filter(n);
lvl = ADCFilter.Current();
//// plot the raw versus filtered signals
//Serial.print(n);
//Serial.print(" ");
//Serial.println(lvl);
// calculate the number of pixels as a percentage of the range
// TO-DO: can be done dynamically by using a running average of min/max audio levels
height = TOP * (lvl - minLvl) / (long)(maxLvl - minLvl);
if(height < 0L) height = 0;
else if(height > TOP) height = TOP;
// turn the LEDs corresponding to the level on/off
for(uint8_t i = 0; i < N_PIXELS; i++) {
// turn off LEDs above the current level
if(i >= height) leds = CRGB(0,0,0);
// otherwise, turn them on!
else leds = Wheel( map( i, 0, N_PIXELS-1, 30, 150 ) );
}
FastLED.show();
}
CRGB Wheel(byte WheelPos) {
// return a color value based on an input value between 0 and 255
if(WheelPos < 85)
return CRGB(WheelPos * 3, 255 - WheelPos * 3, 0);
else if(WheelPos < 170) {
WheelPos -= 85;
return CRGB(255 - WheelPos * 3, 0, WheelPos * 3);
} else {
WheelPos -= 170;
return CRGB(0, WheelPos * 3, 255 - WheelPos * 3);
}
}
驴友花雕
发表于 2022-7-20 15:27:53
实验场景图动态图
驴友花雕
发表于 2022-7-20 15:31:26
实验的视频记录
https://v.youku.com/v_show/id_XN ... hcb.playlsit.page.1
https://v.youku.com/v_show/id_XNTg4NzE0NDMxNg==.html?spm=a2hcb.playlsit.page.1
驴友花雕
发表于 2022-8-12 17:05:23
实验的视频记录(1分49秒)
https://v.youku.com/v_show/id_XNTg5MzA2OTI0MA==.html?spm=a2hcb.playlsit.page.3
https://v.youku.com/v_show/id_XNTg5MzA2OTI0MA==.html?spm=a2hcb.playlsit.page.3
驴友花雕
发表于 2022-8-12 17:12:28
实验的视频记录(50秒)
https://v.youku.com/v_show/id_XNTg5MzA4Mzc4OA==.html?spm=a2hcb.playlsit.page.1
https://v.youku.com/v_show/id_XNTg5MzA4Mzc4OA==.html?spm=a2hcb.playlsit.page.1