基于Arduino与FastLED库的WS2811 LED雷达动画提速求助
问题分析与修复方案
你的代码有三个核心问题导致动画速度无法随时间提升:
- 逻辑反向:你想让动画提速,但代码里是增大
currentDelay(延迟越大,动画越慢),应该是减小延迟来加快速度 - 变量作用域错误:
currentDelay是loop()内的局部变量,每次loop()执行都会被重置为initialDelay,无法保留之前的调整结果 - 时间控制逻辑错误:
while死循环会阻塞程序运行,且没有正确实现“每秒调整一次速度”的逻辑
修复后的代码
#include <FastLED.h> #define LED_DT 3 #define COLOR_ORDER BRG #define LED_TYPE WS2811 #define NUM_LEDS 15 uint8_t max_bright = 55; struct CRGB leds[NUM_LEDS]; // 把需要持续保留的变量设为全局 int currentDelay = 50; // 初始延迟 unsigned long lastSpeedUpdate = 0; // 记录上次调整速度的时间 const int speedAdjustInterval = 1000; // 每秒调整一次 const int minDelay = 10; // 最小延迟,防止动画太快看不清 const int delayStep = 5; // 每次调整的步长 void setLEDs(int K, int N) { FastLED.clear(); for (int i = 0; i < NUM_LEDS; i++) { if (i % N == K) leds[i] = CRGB(200,0,0); } FastLED.show(); } void setup() { Serial.begin(57600); delay(1000); FastLED.addLeds<LED_TYPE, LED_DT, COLOR_ORDER>(leds, NUM_LEDS); FastLED.setBrightness(max_bright); } void loop() { int N = 5; // 执行雷达动画 for (int i = 0; i < N; i++) { setLEDs(i, N); delay(currentDelay); } // 非阻塞式检查是否需要调整速度 if (millis() - lastSpeedUpdate >= speedAdjustInterval) { // 减小延迟来提速,不能低于最小延迟 if (currentDelay > minDelay) { currentDelay -= delayStep; } lastSpeedUpdate = millis(); // 更新上次调整时间 Serial.print("当前延迟: "); Serial.println(currentDelay); // 可选:串口输出当前延迟,方便调试 } }
关键修改说明
- 全局变量存储状态:将
currentDelay和lastSpeedUpdate设为全局变量,确保每次loop()执行时能保留之前的调整结果 - 修正速度逻辑:把“增大延迟”改成“减小延迟”,同时设置
minDelay避免动画过快 - 非阻塞时间控制:用
millis()实现非阻塞的时间间隔检查,不会阻塞动画的正常运行 - 可配置参数:把速度调整间隔、步长、最小延迟都设为常量,方便你根据需求调整
如果需要让动画速度达到最大值后保持稳定,当前代码已经实现;如果需要循环提速/减速,可以再添加逻辑判断currentDelay是否到达阈值后反向调整。
内容的提问来源于stack exchange,提问作者keyboardcowgirl
相关产品推荐
相关产品推荐

