尝试在按下时消除此按钮的抖动
Trying to debounce this button for when pressed
所以我有一个 T 型梁。我正在尝试在按下按钮时实现 D-bounce,这样当按下按钮时,无论多长时间都会出现反跳。目前我让它工作,所以当按下按钮时,它会打印,但由于按钮发出的噪音,它会打印数百次。我已经放入了去抖动代码,但是它没有按预期工作,我不确定为什么。
请查看下面的代码,因为我正在努力实现它。
#include <LoRa.h>
#define SS 18 // GPIO18 −− CS
#define RST 14 // GPIO14 −− RESET
#define DI0 26 // GPIO26 −− I n t e r r u p t Request
#define BAND 868E6 // 868MHz −− UK/European Radio
const int buttonPin = 38;
int buttonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 200;
void setup() {
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
// i n i t i a l i z e S e r i a l Monitor
Serial.begin(115200);
}
int counter = 0;
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
( (millis() - lastDebounceTime) > debounceDelay);
}
else {
Serial.println("HELLO!");
lastDebounceTime = millis();
}
您的代码似乎包含已执行但从未使用过结果的语句。我说的是 ( (millis() - lastDebounceTime) > debounceDelay)
这行。我稍微更改了您的代码以实现适当的去抖动:
bool buttonState = LOW, previousState = HIGH, buttonPressed = false;
void loop()
{
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH)
{
if(previousState == LOW)
{
lastDebounceTime = millis();
}
else if(millis() - lastDebounceTime > debounceDelay && !buttonPressed)
{
// this will be executed once after debouncing
Serial.println("HELLO!");
buttonPressed = true;
}
}
else
{
buttonPressed = false;
}
previousState = buttonState;
}
所以我有一个 T 型梁。我正在尝试在按下按钮时实现 D-bounce,这样当按下按钮时,无论多长时间都会出现反跳。目前我让它工作,所以当按下按钮时,它会打印,但由于按钮发出的噪音,它会打印数百次。我已经放入了去抖动代码,但是它没有按预期工作,我不确定为什么。
请查看下面的代码,因为我正在努力实现它。
#include <LoRa.h>
#define SS 18 // GPIO18 −− CS
#define RST 14 // GPIO14 −− RESET
#define DI0 26 // GPIO26 −− I n t e r r u p t Request
#define BAND 868E6 // 868MHz −− UK/European Radio
const int buttonPin = 38;
int buttonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 200;
void setup() {
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
// i n i t i a l i z e S e r i a l Monitor
Serial.begin(115200);
}
int counter = 0;
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
( (millis() - lastDebounceTime) > debounceDelay);
}
else {
Serial.println("HELLO!");
lastDebounceTime = millis();
}
您的代码似乎包含已执行但从未使用过结果的语句。我说的是 ( (millis() - lastDebounceTime) > debounceDelay)
这行。我稍微更改了您的代码以实现适当的去抖动:
bool buttonState = LOW, previousState = HIGH, buttonPressed = false;
void loop()
{
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH)
{
if(previousState == LOW)
{
lastDebounceTime = millis();
}
else if(millis() - lastDebounceTime > debounceDelay && !buttonPressed)
{
// this will be executed once after debouncing
Serial.println("HELLO!");
buttonPressed = true;
}
}
else
{
buttonPressed = false;
}
previousState = buttonState;
}