【问题标题】:Arduino debounce button with delay带延迟的 Arduino 去抖按钮
【发布时间】:2016-01-07 15:52:23
【问题描述】:

当我尝试使用长线连接开关时,我的 Arduino 遇到了一些问题。

如果我使用较短的电线,我没有问题,但一旦它们被延长,事情就会开始发挥作用。

我想要做的是,当我按下一个按钮时,我希望它输出到一个引脚,保持 2 秒,然后不管按钮是否仍然被按下,都会关闭。

我目前使用的适用于短线的代码是:

// constants won't change. They're used here
// to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  10;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    delay(2000); // wait for a second
    digitalWrite(ledPin, LOW);
  }
}

我在论坛上看到使用 debounce 可以解决这个问题。但是我是 Arduino 新手,不知道如何实现。

我使用了the Arduino button tutorial,并使用了一个 10k 的下拉电阻,如上所述。有什么方法可以通过代码或电阻器/电容允许通过线长

任何帮助表示赞赏。

【问题讨论】:

  • 为什么不起作用?解释实际行为与预期行为

标签: arduino arduino-uno


【解决方案1】:

线长在这里不是问题。您要么有接线故障,要么您的代码与您的预期行为不符。 (你没有提到现在的实际行为是什么。)

不需要额外的开关去抖动,因为在您检测到按钮按下后,您会在一段时间内忽略它的状态。这就是软件去抖通常的情况。

保持2秒,然后不管按钮是否仍然按下关闭。

现在,在您松开按钮之前,输出不会关闭。这样做的原因是,在您将其写入低电平后,您会立即再次检查该按钮,如果仍然按下则将输出写入高电平。您要么需要在下方延迟

digitalWrite(ledPin, LOW);

或者稍微花哨一点,确保在允许再次按下之前释放按钮。

【讨论】:

    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多