-1

我无法向自己解释为什么这段代码在某些情况下可以正常工作而在某些情况下不能正常工作。情况如下:

我正在尝试用 Arduino Nano 切换继电器。因此,我以“Blink”示例为指导。它应该打开大约 5 分钟,然后关闭大约 25 分钟。这是代码:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(2, OUTPUT);               // sets PIN 2 as switcher for the relay
}

// the loop function runs over and over again forever
void loop() {
  int count = 0;
  int run_pump = 300;               // 5 Min run
  int stop_pump = 1500;             // 25 Min stop
  digitalWrite(LED_BUILTIN, LOW);   // turn the LED off (HIGH is the voltage level)
  digitalWrite(2, HIGH);            // turn the pump on
  while(count < run_pump) {
    count++;
    delay(1000);                    // wait for a second
  }
  
  count = 0;              
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on by making the voltage LOW
  digitalWrite(2, LOW);             // turn the pump off
  while(count < stop_pump) {
    count++;
    delay(1000);                    // wait for a second
  }
}

如果我在 Arduino 上运行此代码,它将永远打开继电器。但是:如果我设置10run_pumpstop_pump。它会正常工作!有没有解释为什么这不适用于更大的计数器?太混乱了……

所以这里的代码工作得很好,但是为什么上面的代码不行呢?

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(2, OUTPUT);               // sets PIN 2 as switcher for the relay
}

// the loop function runs over and over again forever
void loop() {
  int count = 0;
  int run_pump = 5;               // 5 sec run
  int stop_pump = 10;             // 10 sec stop
  digitalWrite(LED_BUILTIN, LOW);   // turn the LED off (HIGH is the voltage level)
  digitalWrite(2, HIGH);            // turn the pump on
  while(count < run_pump) {
    count++;
    delay(1000);                    // wait for a second
  }
  
  count = 0;              
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on by making the voltage LOW
  digitalWrite(2, LOW);             // turn the pump off
  while(count < stop_pump) {
    count++;
    delay(1000);                    // wait for a second
  }
}

希望有人有线索....谢谢!汤姆

4

1 回答 1

0

好的,伙计们,我解决了。问题是一个廉价的继电器,它试图与 Arduino 通信……用更好的继电器代替它解决了整个问题。感谢 LED 的创意,这带来了一些石头...... :)

于 2021-04-18T13:22:39.787 回答