so I have a T-Beam. I'm trying to implement D-bounce on the button press, so that when the button is pressed there is a debounce for however long. Currently I have it working so that when the button is pressed, it will print but due to the noise from the button it prints several hundred times. I have put the debounce code in, however it doesn't work as intended and i'm not sure why.
Please have a look at my code below as I'm struggling to implement it.
#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();
}
Your code seems to contain a statement that is executed but the result is never used. I am talking about the line saying ( (millis() - lastDebounceTime) > debounceDelay)
. I changed your code a bit to implement proper debouncing:
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;
}