// https://forum.arduino.cc/t/leading-edge-debouncing/964407/28
const byte buttonPin = 8;
const byte lookingLED = 9;
const int readPeriod = 1000; // absurd. human scale so we can see what really goes on
byte buttonHistory = 0xFF;
unsigned long lastTime, timeChange;
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(lookingLED, OUTPUT);
}
void loop() {
timeChange = (millis() - lastTime);
digitalWrite(lookingLED, (timeChange >= readPeriod) ? HIGH : LOW); // locked out on time?
if (timeChange >= readPeriod) {
buttonHistory <<= 1;
buttonHistory |= digitalRead(buttonPin);
if (buttonHistory == 0xFF) tracePrint("OFF");
else if (buttonHistory) tracePrint("ON");
lastTime = millis();
}
}
// print a new message, and how many times you didn't print the last new message. or don't.
void tracePrint(char *s)
{
static unsigned long tCount;
static char traced[32];
if (strcmp(s, traced)) {
Serial.print(tCount);
Serial.print(" now ");
Serial.println(s);
strcpy(traced,s);
}
else tCount++;
}