不用 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
}