gpt4 book ai didi

c - 如何用 millis() 替换 delay()?

转载 作者:太空宇宙 更新时间:2023-11-04 04:34:45 25 4
gpt4 key购买 nike

过了一会儿,我得到了我想要的最终结果,但我不能使用延迟,因为我需要不同的时间来处理不同的 strip ,所以我需要用 millis 替换 delay() () 在这段代码中:

#include <FastLED.h>
#define NUM_LEDS1 10
#define NUM_LEDS2 6
#define DATA_PIN1 6
#define DATA_PIN2 7
CRGB leds1[NUM_LEDS1];
CRGB leds2[NUM_LEDS2];

void setup() {
FastLED.addLeds<NEOPIXEL, DATA_PIN1>(leds1, NUM_LEDS1);
FastLED.addLeds<NEOPIXEL, DATA_PIN2>(leds2, NUM_LEDS2);
}

int dot_delay1[ ] = { 100,200,300,400,500,600,700,800,900,1000 };
int dot_delay2[ ] = { 100,200,300,400,500,600 };

void loop() {
for(int dot = 0; dot < NUM_LEDS1; dot++)
for(int dot = 0; dot < NUM_LEDS2; dot++)
{
leds1[dot] = CRGB::Blue;
leds2[dot] = CRGB::Blue;
FastLED.show();
leds1[dot] = CRGB::Black;
leds2[dot] = CRGB::Black;
delay( dot_delay1[ dot ] );
// this is where I need to put the second delay,
// but I can't put more then 1 delay.
// I need to refactor my code with millis() function instead of delay()
}
}

最佳答案

您可以使用以特殊频率或时间执行的非阻塞代码模式。在下文中,我将向您提供一个简短示例,说明如何在不阻塞主循环的情况下替换 delay(1000)delay(5000)。此外,您可以检查 stackoverflow 是否有类似的帖子(例如 Pause without Delay() arduino )。

// 1 sec. frequency
unsigned long interval=1000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.

// 5 sec. frequency
unsigned long interval1=5000; // the time we need to wait
unsigned long previousMillis1=0; // millis() returns an unsigned long.

void setup() {
//...
}

void loop() {

// other CMD's...

// replace delay(1000)
if ((unsigned long)(millis() - previousMillis) >= interval) {
previousMillis = millis();
// every first second
// ...
}

// other CMD's...

// replace delay(5000)
if ((unsigned long)(millis() - previousMillis1) >= interval1) {
previousMillis1 = millis();
// every fifth second
// ...
}

// other CMD's...
}

关于c - 如何用 millis() 替换 delay()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32037217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com