Sub topic 10
Blinking and Button Handling Together
This chapter combines the two techniques from earlier chapters. A millis()-based blink and a timestamp-debounced button run in the same loop(), and neither one blocks the other. It assumes you can write setup() and loop(), use pinMode(), digitalRead() and digitalWrite(), and wire a pushbutton and an LED. It also assumes you have read the earlier chapters on INPUT_PULLUP, contact bounce, millis() and unsigned rollover.
Why combine them
Each technique works alone. A delay() blink makes the button feel dead, because the sketch only reads the pin between delays. A debounce routine is easy to write with delay(), but it freezes everything else while it waits.
The fix is to give every task its own variables and run all the checks on every pass through loop(). No task waits. Each one asks a quick question and moves on:
- Has the blink interval elapsed?
- Has the button reading been stable long enough?
If the answer is no, the task does nothing and loop() continues. A pass through loop() then takes microseconds, so each task is checked thousands of times per second.
The working model
Think of loop() as a dispatcher that runs a fixed list of small tasks in order. Each task follows three rules:
- It keeps its own state in variables that persist between passes.
- It reads the clock with
millis()and compares it to its own timestamp. - It returns quickly. It never uses
delay()or awhileloop that waits for something.
The combined sketch
This sketch blinks the built-in LED every 500 ms. A button connects pin 2 to GND, and each debounced press toggles a second LED on pin 8. Wire pin 8 through a resistor (about 220 Ω) to an LED, with the other end of the LED to GND.
const uint8_t BUTTON_PIN = 2;
const uint8_t LED_PIN = 8;
const unsigned long BLINK_MS = 500;
const unsigned long DEBOUNCE_MS = 30;
// Blink task state
unsigned long previousBlink = 0;
bool blinkState = LOW;
// Button task state
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastChangeTime = 0;
bool ledOn = false;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
// Task 1: blink without blocking
if (now - previousBlink >= BLINK_MS) {
previousBlink = now;
blinkState = !blinkState;
digitalWrite(LED_BUILTIN, blinkState);
}
// Task 2: debounced button
int reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
lastChangeTime = now;
lastReading = reading;
}
if ((now - lastChangeTime >= DEBOUNCE_MS) && (reading != stableState)) {
stableState = reading;
if (stableState == LOW) { // pressed: the pin is pulled to GND
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
}
}
}The blink keeps its rhythm while you press the button, and the button responds about 30 ms after the contact settles. Each task has its own timestamp (previousBlink and lastChangeTime), so changing one interval never affects the other.
Reading the clock once per pass
The sketch calls millis() once at the top and stores it in now. Both tasks then use the same value. This has two benefits:
- The tasks see a consistent moment in time. If the value changed between two calls, two tasks could disagree about which millisecond it is.
- The code is shorter and a little faster.
One caveat is that now can be slightly stale if an earlier task takes a long time. In this sketch the tasks take microseconds, so it does not matter. If you add a slow task, such as a long Serial.print() or an LCD update, read millis() again where precision matters.
Separate state for each task
The most common mistake in combined sketches is sharing a timestamp between tasks. Suppose you reuse previousMillis for both the blink and the debounce. Each task then overwrites the other's reference time. The blink would restart every time the button moves, and the debounce would restart every time the LED toggles. Give each task its own timestamp and its own state variables, and name them after the task.
Why the debounce does not drift or miss presses
The debounce logic has two parts that work together:
- When the raw reading differs from
lastReading, the code records the time of the change. Every bounce resets the timer. - The code accepts a new state only when the raw reading has been unchanged for
DEBOUNCE_MSand differs fromstableState.
Because the acceptance test compares against stableState, a held button triggers the action once. After the press is accepted, reading equals stableState, so the second condition is false on every later pass. The release is accepted the same way. It updates stableState to HIGH, but the if (stableState == LOW) check means the release does nothing visible.
All the elapsed-time tests use unsigned subtraction. For example, now - lastChangeTime >= DEBOUNCE_MS keeps working after millis() wraps around, about 49.7 days after boot. This holds as long as every timestamp and every now value is an unsigned long.
A table of timelines
The table below traces the sketch over a short sequence. The button is pressed at 1000 ms and bounces until 1008 ms. It is released at 2000 ms and bounces until 2004 ms.
| Time (ms) | Raw reading | Event in the sketch | LED on pin 8 |
|---|---|---|---|
| 1000 | LOW | Change seen, `lastChangeTime` = 1000 | off |
| 1003 | HIGH | Bounce, `lastChangeTime` = 1003 | off |
| 1008 | LOW | Final change, `lastChangeTime` = 1008 | off |
| 1038 | LOW | Stable for 30 ms, accepted as press | toggles on |
| 1500 | LOW | Blink fires, button unchanged | on |
| 2000 | HIGH | Release seen, `lastChangeTime` = 2000 | on |
| 2004 | HIGH | Release bounce settles (final change at 2004) | on |
| 2034 | HIGH | Stable for 30 ms, release accepted, no action | on |
The blink fires at 500 ms intervals throughout (for example at 1500 and 2000). Nothing in the button logic delays it.
Adding a third task
The same pattern extends to more tasks. Suppose you want to print the button count to the serial monitor once a second. Add a third block with its own timestamp:
const uint8_t BUTTON_PIN = 2;
const uint8_t LED_PIN = 8;
const unsigned long BLINK_MS = 500;
const unsigned long DEBOUNCE_MS = 30;
const unsigned long REPORT_MS = 1000;
unsigned long previousBlink = 0;
bool blinkState = LOW;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastChangeTime = 0;
bool ledOn = false;
unsigned int pressCount = 0;
unsigned long previousReport = 0;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - previousBlink >= BLINK_MS) {
previousBlink = now;
blinkState = !blinkState;
digitalWrite(LED_BUILTIN, blinkState);
}
int reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
lastChangeTime = now;
lastReading = reading;
}
if ((now - lastChangeTime >= DEBOUNCE_MS) && (reading != stableState)) {
stableState = reading;
if (stableState == LOW) {
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
pressCount++;
}
}
if (now - previousReport >= REPORT_MS) {
previousReport = now;
Serial.print("Presses: ");
Serial.println(pressCount);
}
}Each task costs one timestamp and a few state variables. The tasks stay independent, so you can change one interval without touching the others.
Gotchas and common errors
- Using
delay()anywhere inloop(). A singledelay(10)in a "small" task adds 10 ms of latency to every other task. Remove it or convert it to a timestamp check. - Updating the timestamp with the wrong value. Setting
previousBlink = nowkeeps a steady average rate if the check runs a little late, but each late firing pushes the schedule back by the lateness. If you need a long-term exact rate, usepreviousBlink += BLINK_MSinstead. This keeps the schedule fixed to the original grid. The catch is that after a long stall the loop fires repeatedly to catch up, so use it only whenloop()is never blocked for longer than one interval. - Mixing integer types. Storing a
millis()value in anintoverflows after about 32 seconds on an 8-bit board such as the Uno, whereintis 16 bits. Useunsigned longfor every timestamp and interval. - Slow code in
loop(). If a task takes longer than the debounce window, you can miss a whole press and release cycle. Keep each task short, and avoid longSerialoutput, blocking sensor libraries, anddelay(). - Forgetting that the button is inverted. With
INPUT_PULLUP,LOWmeans pressed. A condition written asstableState == HIGHfires on release. - Resetting the debounce timer on every pass. Update
lastChangeTimeonly when the reading changes. If you update it on every pass, the elapsed time never reaches the threshold.
Choosing the debounce and blink values
The blink interval has no effect on debouncing, because the two tasks are independent. The debounce time does matter to the feel of the button. Typical switches settle within 5 to 20 ms, and 30 ms leaves a margin. Values above about 100 ms make the button feel sluggish and can drop fast double-presses. Measure with the serial monitor if a particular button misbehaves. Print the time between raw changes for a few presses, then set the debounce a little above the longest bounce you see.
Structuring larger sketches
Once a sketch has more than two or three tasks, loop() gets crowded. A simple remedy is to move each task into its own function that uses static local variables or globals, and have loop() read the clock and call them:
const uint8_t BUTTON_PIN = 2;
const uint8_t LED_PIN = 8;
void blinkTask(unsigned long now) {
static unsigned long previous = 0;
static bool state = LOW;
if (now - previous >= 500) {
previous = now;
state = !state;
digitalWrite(LED_BUILTIN, state);
}
}
void buttonTask(unsigned long now) {
static int lastReading = HIGH;
static int stableState = HIGH;
static unsigned long lastChange = 0;
static bool ledOn = false;
int reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
lastChange = now;
lastReading = reading;
}
if ((now - lastChange >= 30) && (reading != stableState)) {
stableState = reading;
if (stableState == LOW) {
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
}
}
}
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
blinkTask(now);
buttonTask(now);
}A static local keeps its value between calls but is visible only inside its function. That removes the risk of two tasks sharing a variable by accident. The trade-off is that you cannot easily read a task's state from elsewhere. If the button task needs to tell another task that a press happened, return a bool or write to a global flag.
Checking your understanding
Exercise
In the combined sketch, a developer changes the blink code to use the same variable lastChangeTime that the button code uses, to "save memory". What symptoms would you expect, and why?
Show answer
Both tasks would overwrite each other's reference time. The blink block sets the timestamp each time it fires, so the button's elapsed time keeps restarting. A press could take longer than 30 ms to accept, or never be accepted if the blink interval is shorter than the debounce time. In the other direction, each button change resets the blink's timer, so the blink delays or skips. Each task needs its own timestamp.
Exercise
A sketch has a 500 ms blink, a 30 ms debounce, and a function that calls delay(200) once per pass to "slow down" serial output. What is the worst-case delay before a press is accepted, and how would you fix it?
Show answer
Each pass takes at least 200 ms, so the sketch samples the pin only about every 200 ms. A press is noticed up to 200 ms late, and the 30 ms stability check is measured in samples 200 ms apart. Short bounces fall between samples and are not seen at all. The blink is also delayed by up to 200 ms. Remove the delay(200) and print on a millis() timer, for example once per second.
Exercise
Why does the debounce code compare the reading to stableState rather than only checking that the reading has been stable for 30 ms?
Show answer
Without the reading != stableState check, the stable-time condition stays true for as long as the button is held. The action would fire on every pass. Comparing to stableState makes it true only on the pass where the accepted state changes, so each press produces one event.