首页 > 解决方案 > 尝试在按下时消除此按钮的抖动

问题描述

所以我有一个T-Beam。我正在尝试在按下按钮时实现 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();
    }





标签: c++arduinolora

解决方案


您的代码似乎包含一个已执行但从未使用结果的语句。我说的是行话( (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;
}

推荐阅读