I'm running into issue properly reading a button connected to a digital I/O pin on my Adafruit Feather HUZZAH ESP8266 device.
I've implemented the debouncing script exactly as the Arduino provided example shows, but if I add a print statement to my setup loop:
void setup() {
Serial.begin(230400);
Serial.println("Starting");
pinMode(buttonPin, INPUT_PULLUP);
}
I trigger a reading of the switch on every reset cycle. Commenting out the print statement will avoid the problem so it doesn't appear to be related to the debouncing script.
In addition, I can replicate the problem on any digital I/O pin even when there is no pin connected. Once I get past the setup function, everything works as intended. Here's my whole setup code (again, copied from the example):
const int buttonPin = 13;
int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
Serial.begin(230400);
Serial.println("Starting");
pinMode(buttonPin, INPUT_PULLUP);
lastDebounceTime = millis();
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
Serial.println("A");
}
}
lastButtonState = reading;
}
And here's the output of my serial monitor (with no delays on reset):
Starting
A
I can avoid this by just ignoring the first button switch but it seems odd that this is happening and I can't find any explanations for what's going on.
Serial.println
adds to (a) time spent insetup
, and (b) time spent doing "things" before the serial buffer is written out. It seems more likely there's a flaw in the debounce logic, particularly iflastDebounceTime
is initialized to0
(a Long Time Ago to the controller).