Sub topic 12
Toggling an LED on Each Press
This chapter combines the earlier pieces into one behavior: each press of a push button flips an LED between on and off. It assumes you have read the chapters on INPUT_PULLUP and active-low logic, contact bounce, millis-based debouncing, and press detection. You should also be comfortable with digitalWrite and with wiring a button between a pin and GND.
What a toggle needs
Holding the LED on while the button is held is easy, because the output copies the input. A toggle is different. The LED must stay in its new state after you let go, so the sketch has to remember something. Three parts are required:
- A clean reading. The button must be debounced, or one press will flip the LED several times.
- An event. The sketch must react once per press, at the moment the state changes. It must not react on every pass through
loop()while the button is down. - Memory. A variable holds the LED's intended state, and each event inverts it.
If any part is missing, you get a typical failure. Without debouncing, the LED seems to change at random. Without event detection, it flickers while the button is held. Without memory, it only follows the button.
The complete sketch
Wire the button between pin 2 and GND. No external resistor is needed, because the sketch uses the internal pull-up. The LED is the board's built-in LED on pin 13.
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);
}
}
}How the pieces map to the three needs
The variables fall into groups:
readingis the raw value from this pass. It may be noisy.lastReadingis the raw value from the previous pass. Comparing the two detects any change, including bounce.lastChangeTimeis the time of the most recent raw change. Each bounce pushes it later.stableStateis the accepted, debounced state. Only this value is trusted.ledOnis the memory. It records whether the LED should be lit.
The first if is the bounce filter. Every raw change restarts the 25 ms timer. The second if fires only when two things are true: the raw reading has been steady for at least 25 ms, and it differs from the accepted state. That is the debounced edge.
The line if (stableState == LOW) selects which edge counts. With INPUT_PULLUP, a press is the HIGH-to-LOW transition, so the sketch toggles on press. On release, stableState is updated to HIGH, but no toggle happens.
The ternary ledOn ? HIGH : LOW turns the bool into a pin level. You could also write digitalWrite(ledPin, ledOn), because true and false convert to 1 and 0. The explicit form is clearer.
Tracing one press
Suppose the button is pressed at t = 100 ms and the contacts bounce for a few milliseconds. The table shows what the sketch sees. Times are approximate and loop() runs thousands of times per millisecond, so only the interesting passes are listed.
| Time (ms) | Raw reading | What the code does | `stableState` | LED |
|---|---|---|---|---|
| 0 to 99 | HIGH | No change, nothing happens | HIGH | off |
| 100 | LOW | Raw change, `lastChangeTime` = 100 | HIGH | off |
| 102 | HIGH | Bounce, `lastChangeTime` = 102 | HIGH | off |
| 104 | LOW | Raw change, `lastChangeTime` = 104 | HIGH | off |
| 105 to 128 | LOW | Steady, but under 25 ms since last change | HIGH | off |
| 129 | LOW | 25 ms steady, differs from stable, accept | LOW | on (toggled) |
| 130 to 400 | LOW | Reading equals `stableState`, nothing happens | LOW | on |
When the button is released, the same filter runs in the other direction. stableState becomes HIGH about 25 ms after the last bounce, and no toggle happens. The next press toggles the LED off.
Keeping the logic reusable
The sketch above mixes button handling with the toggle. Moving the debounce and edge logic into a function makes loop() read like the behavior you want. The function below returns true for exactly one call per press.
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;
bool buttonPressed() {
int reading = digitalRead(buttonPin);
if (reading != lastReading) {
lastChangeTime = millis();
lastReading = reading;
}
if ((millis() - lastChangeTime) >= debounceMs && reading != stableState) {
stableState = reading;
return stableState == LOW;
}
return false;
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (buttonPressed()) {
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
}This behaves the same as the first sketch. The function has one rule: call it once per loop() pass. Calling it twice in one pass would read the pin twice and could skip or duplicate an edge. To support several buttons, you would turn the state variables into arrays or a struct, one set per button. Sharing one set of variables between buttons breaks the filter.
Why the LED state lives in a variable
On AVR boards such as the Uno, digitalRead(ledPin) on an output pin returns the level you last wrote, so you could toggle with digitalWrite(ledPin, !digitalRead(ledPin)). That works, but it ties your logic to a hardware behavior that differs between cores and is not guaranteed everywhere. A bool is portable. It also lets the same state drive other things, such as a log message or a second output, and it survives changing the LED's wiring from active-high to active-low.
Edge cases and common errors
The LED flickers while the button is held
The sketch is toggling on the level instead of the edge. Check that the toggle sits inside the block guarded by reading != stableState. If you toggle whenever stableState == LOW, the LED flips on every pass.
Some presses do nothing
Three causes are common:
debounceMsis too large. A 25 ms window can swallow a very quick tap only if the press is shorter than 25 ms, which is rare for fingers. At 200 ms or more, fast double taps are lost.- The code uses
delay()for long periods elsewhere inloop(). A press shorter than the delay can start and end between two reads. - The button is worn and bounces longer than the window. Raise
debounceMstoward 50 ms and test again.
Some presses toggle twice
The debounce window is too short for this button. Cheap tactile switches can bounce for 5 to 10 ms, and some old or dirty ones for more. Increase debounceMs. You can measure the real value by counting raw changes per press with Serial, but printing inside the fast loop is only for testing.
Everything is inverted
With an external pull-down, a press reads HIGH, so the edge you want is LOW to HIGH. Either change the initial values to LOW, change the comparison to stableState == HIGH, and use INPUT, or switch to the internal pull-up wiring this chapter uses. Mixing the two, for example INPUT_PULLUP with the comparison for HIGH, toggles on release instead of press.
The LED toggles once at power-up
If the button is held down while the board starts, the first accepted reading is LOW. The sketch sees a HIGH-to-LOW change from its assumed starting state and toggles once. To avoid this, initialize the variables from the real pin level in setup():
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
lastReading = digitalRead(buttonPin);
stableState = lastReading;
}What happens when `millis()` rolls over
millis() returns an unsigned long that wraps to 0 after about 49.7 days. The expression millis() - lastChangeTime is still correct across the wrap, because unsigned subtraction wraps the same way. This only holds if both values are unsigned long. Storing the time in an int breaks the filter after about 32 seconds.
Toggle on release instead
Some interfaces feel better if the action happens when the finger lifts, because the user can slide away to cancel. Change the test to stableState == HIGH. The debounce logic is identical.
Where interrupts fit
An interrupt could call a function the moment the pin changes, which seems ideal for a toggle. In practice, bounce produces a burst of interrupts for each press, so you still need the 25 ms filter inside the handler or beside it. Handlers also cannot use delay() and have to keep shared variables volatile. For a human-operated button that is polled thousands of times a second, polling is simpler and just as responsive. Interrupts are worth the added complexity when the main loop is busy or blocked for long stretches, or when the board sleeps and a button must wake it.
Exercise
A student changes the sketch so the toggle line ledOn = !ledOn; sits directly after if (reading != stableState), but outside the if (stableState == LOW) block. The wiring is a button between pin 2 and GND with INPUT_PULLUP. How many times does the LED change state for one complete press and release, and why does the user perceive this as the button not working properly?
Show answer
The LED changes state twice per press and release: once on the press (stableState becomes LOW) and once on the release (stableState becomes HIGH). The LED ends up in its original state after the button is let go. While the button is held it looks correct (on), but it turns off again on release, so it behaves like a momentary button and not a toggle. The fix is to put the toggle inside the if (stableState == LOW) block so only the press edge counts.
Exercise
You build a version that toggles on release, using a button wired between pin 2 and GND with INPUT_PULLUP. Which one comparison do you change in the first sketch, and to what? Name one situation where toggling on release is the better design.
Show answer
Change if (stableState == LOW) to if (stableState == HIGH), because a release is the LOW-to-HIGH transition with the internal pull-up. Toggling on release is better when the user should be able to cancel by sliding off the button, or when the press might be part of a longer gesture such as a long press, where the action should wait until the intent is clear.