【问题标题】:Trying to press a button and toggle an LED flash at 2Hz until i press the button again [closed]尝试按下按钮并以 2Hz 切换 LED 闪烁,直到我再次按下按钮 [关闭]
【发布时间】:2021-12-02 08:11:29
【问题描述】:

我正在努力学习编码,这真的让我很难过,所以我想我会问你们可爱的人。

基本上我正在尝试按下一个按钮并打开一个 LED 开关,该开关在一秒钟内闪烁两次,这将是连续的,直到我再次按下按钮将其关闭。

这是我目前的代码。

bool latch = false;

void setup(){
pinMode(1, INPUT);
pinMode(13, OUTPUT);
}
void loop(){
if (digitalRead(1)){
  latch = !latch;
}
if (latch == 1){
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}else{
  digitalWrite(13, LOW)
}
}

【问题讨论】:

  • 贴出来的代码怎么不能满足你的需求?
  • 在我再次尝试按下按钮并且 LED 一直闪烁之前,它一直有效,我不知道为什么
  • 尝试正确缩进代码,然后仔细查看。此外,为了便于阅读,请选择 1/0 或 true/false。

标签: c++ arduino toggle led


【解决方案1】:

由于调用了delay(1000),您的代码要求您在调用digitalRead(1) 的瞬间按下按钮。 delay() 正在运行时,Arduino 无法监听按钮按下。此外,您拨打delay(1000) 两次,LED 会在两秒内闪烁一次,而不是在一秒钟内闪烁两次。

解决方案是创建一个计数器来计算自上次打开或关闭 LED 以来经过了多少毫秒。循环将每毫秒将 1 加到 counter,因此当 counter 等于或大于 500(半秒)时,LED 会打开或关闭。

这是一个程序,当按钮被按下时,LED 开始闪烁(1 秒内打开和关闭),当再次按下按钮时停止闪烁。代码中有更多解释。

bool latch = false;
bool led_state = false;

// How many milliseconds it has been since the last LED state change
int counter = 0;

void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
}
void loop() {

  // Check if the button was pressed
  if (digitalRead(2)){

    // If the button was pressed, wait half a second before toggling latch,
    // to "de-bounce" the button (prevent it from sending multiple clicks for
    // one press)
    delay(300);
    latch = !latch;
  }

  // If we are in on state (latch == true)...
  if (latch) {

    // ...add 1 to the counter and wait 1 millisecond...
    counter += 1;
    delay(1);

    // ...and toggle the LED state if 500 milliseconds have passed.
    // This we know because counter >= 500.
    if (counter >= 500) {
      if (led_state == true) led_state = false;
      else if (led_state == false) led_state = true;
      counter = 0;
    }
    digitalWrite(13, led_state);

  // If we are in off state, turn the LED off
  } else {
    digitalWrite(13, false);
  }
}

【讨论】:

  • 非常感谢我对这一切真的很陌生,这对我很有帮助。祝你有个愉快的夜晚,祝你一切顺利。
  • 如果我的回答令人满意,请考虑接受:-)。
【解决方案2】:

我用一个类似于我假设您设置的模拟器进行了一些实验(使用它来设置您的情况以解决未来的 Arduino 问题,以便人们更容易理解和帮助)

https://wokwi.com/arduino/projects/312378906051084864

除了在这里添加一个缺少的分号,并使用我认为你的编程知识是

之前

}else{
  digitalWrite(13, LOW)
}

之后

}else{
  digitalWrite(13, LOW);
}

我对您的 if 语句进行了小幅更改,这使其适用于某些特定用途,您必须点击按钮将其打开并在您认为间隔即将到期时按住它。这是因为您使用了延迟功能,该功能基本上会停止程序的所有执行,直到间隔结束。因此,与您的按钮关联的引脚必须在延迟间隔之后以及在评估闩锁期间为高电平

if (digitalRead(1)){
  latch = true;
}else{
latch = false;
}

推荐的替代品

如果您对更好的更高级的代码应用感兴趣,我发现了这个参考资料,它提供了一种不使用延迟功能使 LED 闪烁的方法

https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多