Arduino使用 millis()延时实现


unsigned long previousMillis = 0;
boolean delayState = false;

void setup() {
  pinMode(7, INPUT_PULLUP);
  Serial.begin(115200);
}

void loop() {
  ///////////////////////按键引脚触发延时//////////////////////////
  if (digitalRead(7) == LOW) {
    delayState = true;
  }
  if (delayState == true) {
    delay(100);
    if (doDelayMillisTime(5000 , false) == true) {
      Serial.println("key pin delayMillisTime!");
      delayState = false;
    }
  }

  ////////////////////////延时//////////////////////////////
  if (doDelayMillisTime(5000 , false) == true) {
    Serial.println("delayMillisTime!");
  }
}

boolean doDelayMillisTime(long interval , boolean state) {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    state = !state;
  }
  return state;
}

你可能感兴趣的:(Arduino)