Sub topic 3
Why one press can look like many
This chapter assumes you know the setup and loop structure, can read a pin with digitalRead, and have wired a button to an INPUT_PULLUP pin. You should also know how millis() returns elapsed time.
Why one press can look like many
A mechanical push button closes a pair of metal contacts. When the contacts meet, they bounce for a few milliseconds before settling. Your code sees several HIGH-to-LOW transitions for one press. A loop that reads the pin thousands of times per second counts every bounce as a separate press.
Debouncing a button with millis
Debouncing accepts a new state only after the raw reading stays unchanged for a set time. Using millis() instead of delay() keeps the loop running while the code waits.
const int buttonPin = 2;
const int ledPin = LED_BUILTIN;
const unsigned long debounceMs = 25;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastChangeTime = 0;
bool ledOn = false;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastReading) {
lastChangeTime = millis();
lastReading = reading;
}
if ((millis() - lastChangeTime) >= debounceMs && reading != stableState) {
stableState = reading;
if (stableState == LOW) {
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
}
}The code accepts a change only after the reading has been stable for 25 ms.
Detecting a press instead of a held level
stableState tells you whether the button is held down. To react once per press, act only on the moment the stable state changes from HIGH to LOW. The check stableState == LOW inside the change branch does this.
Toggling an LED on each press
Each accepted press flips ledOn. Holding the button does not flip it again, because the edge check fires only once per press.
Interrupts for button input: when and why to avoid them
An interrupt runs a function when a pin changes, so the loop does not need to poll the pin. Interrupts still have costs for buttons. Bounce fires the interrupt several times, so the handler still needs debouncing. The processor also disables interrupts while a handler runs, so millis() does not advance inside it, and delay() does not work there. For one button in a polling loop, the debounced approach above is simpler and usually enough.
Exercise
Change debounceMs to 0. What happens when you press the button?
Show answer
Any change in the raw reading is accepted immediately. Bounce then toggles the LED several times per press, so the debounce is gone.