不用 delay() 执行多个任务

如果你有多个任务以不同的间隔重复执行,请使用此示例作为起点:

unsigned long intervals[] = {250,2000}; //this defines the interval for each task in milliseconds
unsigned long last[] = {0,0};           //this records the last executed time for each task

void setup() {
  pinMode(LED_BUILTIN, OUTPUT); //set the built-it led pin as output
  Serial.begin(115200);         //initialize serial
}

void loop() {
  unsigned long now = millis();
  if(now-last[0]>=intervals[0]){ last[0]=now; firstTask(); }
  if(now-last[1]>=intervals[1]){ last[1]=now; secondTask(); }
  
  //do other things here
}

void firstTask(){
  //let's toggle the built-in led
  digitalWrite(LED_BUILTIN, digitalRead(LED_BUILTIN)?0:1);
}

void secondTask(){
  //say hello
  Serial.println("hello from secondTask()");
}

要添加另一个每 15 秒执行一次的任务,请扩展变量 intervalslast

unsigned long intervals[] = {250,2000,15000};
unsigned long last[] = {0,0,0};

然后添加 if 语句来执行新任务。在这个例子中,我将其命名为 thirdTask

if(now-last[2]>=intervals[2]){ last[2]=now; thirdTask(); }

最后声明函数:

void thirdTask(){
  //your code here
}