Arduino UNO 解决多个重叠定时器循环

Ardunio UNO solve multiple overlapping timer loops

我一直在编写两个重叠的循环来切换泵继电器。如果计时器“delayPump”结束(低),则计时器“runnningPump”(高)应该启动。

我想有些疯狂的数学,老实说这个循环已经让我发疯了,因为它应该很容易!!!

有线索吗??

#define pumpSwitch_1 8
int delayPump = 10000; //delay time
int runnningPump = 5000; // running Timer
bool pumpState = LOW; 
unsigned long TimerPump = 0;
unsigned long TimerDelay = 0;

void setup() {
  pinMode(pumpSwitch_1, OUTPUT);
  digitalWrite(pumpSwitch_1, LOW);

  TimerPump = millis();
  TimerDelay = millis(); 
}

void loop() {
  digitalWrite(pumpSwitch_1, pumpState);

  if (pumpState == HIGH){
    if((millis() - TimerPump) >= runnningPump){
      pumpState = LOW;
      TimerPump = millis() + delayPump;
      }
  }else {
    if((millis() - TimerDelay) >= delayPump){
      pumpState = HIGH;
      TimerDelay = millis() + runnningPump;
      }
    }
}

我想这就是你需要的:

您只需要一个 Timer 变量,每次切换状态时,将其设置为当前时间,即 millis().

#define pumpSwitch_1 8
int delayPump = 10000; //delay time
int runnningPump = 5000; // running Timer
bool pumpState = LOW; 
unsigned long Timer = 0;

void setup() {
  pinMode(pumpSwitch_1, OUTPUT);
  digitalWrite(pumpSwitch_1, LOW);

  Timer = millis();
}

void loop() {
  digitalWrite(pumpSwitch_1, pumpState);

  if (pumpState == HIGH) {
    if ((millis() - Timer) >= runnningPump) {
        pumpState = LOW;
        Timer = millis();
    }
  } else {
    if ((millis() - Timer) >= delayPump) {
        pumpState = HIGH;
        Timer = millis();
    }
  }
}