Learning Goals 5 min
By the end of this lesson you will be able to:
- Reproduce the bounce bug by running a press-counter sketch with no debounce — and watch a single physical press register as 2, 3 or even 4 counts on the Serial Monitor.
- Explain in one sentence what physically happens at the metal contacts of a button in the first few milliseconds of a press.
- Add a
delay(20)at the end ofloop()to filter out the bounce — and explain why 20 ms is the right size: long enough to outlast the bounce, short enough to feel instant.
Warm-Up 10 min
The state-change pattern from L01-19 looked clean on paper — and worked perfectly when you pressed the button slowly and steadily. But the 🟡 task asked you to press fast and watch the Serial Monitor, where you may have seen something odd.
Quick-fire puzzle
Noah wires the L01-19 press-counter sketch and presses the button exactly five times in quick succession. The Serial Monitor shows:
1
2
3
5
6
9
10- How many presses does Noah think he made, and how many does the Arduino think he made?
- Where did the extra counts come from? Did Noah actually press the button more than five times?
- What might be happening at the moment Noah's finger pushes the button down — in the metal contact inside the button — that would explain extra counts?
Reveal the answer
- Noah pressed it 5 times; the Arduino counted 10. (Or maybe 7, or 11 — the number changes from try to try.)
- The extra counts came from inside the button itself. Noah didn't press it more than five times; the button "lied" to the Arduino by reporting some presses multiple times.
- When two pieces of metal slap together, they don't make a clean instant connection — they vibrate against each other for a few milliseconds, like a tiny door slamming. The Arduino is fast enough to see each vibration as a separate press.
This effect is called contact bounce, and every mechanical switch in the world does it. Today's whole lesson is two simple ideas: see the bounce, then filter it.
New Concept 20 min
The big idea — buttons aren't as clean as they look
The push button in your kit has two metal pieces inside it. When you press, a tiny spring pushes one piece down onto the other. Because both pieces are slightly springy, they don't touch and stay put — they bounce, like a coin dropped onto a tabletop. For roughly 3 to 20 milliseconds after the initial contact, the connection rapidly opens and closes a few times before settling into a steady "closed" state.
From the Arduino's point of view, those few milliseconds look like a frantic sequence of presses and releases. That's where Noah's extra counts came from.
What bounce looks like as a signal
Why the L01-19 state-change pattern is fooled
Recall the four-step pattern: read, compare, act on change, remember. During the bounce region, the signal genuinely does change six or seven times. The pattern faithfully detects each one. The pattern isn't broken — the button is "lying" within its specifications, and our code is taking the lies at face value.
The simplest fix — a short delay
Adding a delay(20) at the end of loop() has a magical effect: it slows the loop down so that between two reads, at least 20 milliseconds pass. By the time the second read happens, the bounce region has long finished and the signal is settled. The pattern sees only one transition per press.
Why 20 ms?
- Long enough. Bounce is usually 3–10 ms; 20 ms gives a generous safety margin.
- Short enough. Humans perceive delays under about 50 ms as "instant". The button still feels snappy.
- Tradition. Almost every Arduino tutorial in the world uses 20 or 50 ms. They're both fine.
The pattern
void loop() {
// ... read, compare, act, remember ... (same as L01-19)
delay(20); // hide the bounce
}One line. Always at the very end of loop(). That's it.
Reuse the L01-17 wiring
Today's hardware is unchanged from the last two lessons: button on D7 with INPUT_PULLUP, onboard LED on pin 13. No new wires, no new components. Here is that circuit again, in the engineer's view — worth a second look now that you know the resistor lives inside the chip.
D7 is watching flicks between 5 V and 0 V several times.Why it matters
Every digital input from a mechanical source — buttons, switches, rotary encoders, even reed switches near a magnet — has some kind of bounce. Without debouncing, those inputs are unusable for any sketch that cares about counting events accurately. Today's delay(20) is the simplest, cheapest, most universal fix. Real engineers use it as their first attempt; only if the application demands something faster do they switch to the non-blocking version you'll meet later in Level 2.
Worked Example 20 min
Goal: see the bounce bug for yourself, then fix it with one line of code.
Step 1 — type the broken counter (no debounce)
Open a new sketch called bounce-bug. Type this from scratch — it's the L01-19 press-counter, with the delay(20) deliberately removed:
const int BUTTON_PIN = 7;
const int LED_PIN = 13;
int lastButton = HIGH;
int pressCount = 0;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int currentButton = digitalRead(BUTTON_PIN);
if (currentButton != lastButton) {
if (currentButton == LOW) {
pressCount = pressCount + 1;
Serial.println(pressCount);
}
}
lastButton = currentButton;
}Step 2 — upload and watch the bug
- Open the Serial Monitor (magnifying-glass icon, top right of the IDE). Set it to 9600 baud.
- Press the button slowly, once. You should see one number appear. Good.
- Press quickly, five times in a row. Look at the column of numbers.
- Repeat the five fast presses a few more times. You'll often see the count jump by 2, 3, or even more on a single physical press.
You're now looking at bounce. Each "extra" count is one of those metal-contact vibrations that the state-change pattern caught.
Step 3 — slow down (or speed up) and notice the pattern
- Slow, deliberate presses (one per second): the count is usually correct. Bounce still happens, but with a 1-second gap between presses, you can't perceive a few extra counts in the noise.
- Fast presses (4 per second): the count is always too high. Bounce becomes obvious.
- A single press where you push down extra-hard: bounce can be longer, more extra counts.
- A single press where you push down extra-soft: sometimes bounces, sometimes doesn't.
The behaviour is not deterministic. Without debouncing, the sketch's behaviour depends on the user's finger pressure, the button's age, the temperature, even ambient humidity. That's unacceptable for a real product.
Step 4 — add the one-line fix
At the very end of loop(), just before the closing brace, add:
delay(20); // hide the bounce
}Re-upload. Try the five-fast-presses test again.
Step 5 — the fixed sketch
const int BUTTON_PIN = 7;
const int LED_PIN = 13;
int lastButton = HIGH;
int pressCount = 0;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int currentButton = digitalRead(BUTTON_PIN);
if (currentButton != lastButton) {
if (currentButton == LOW) {
pressCount = pressCount + 1;
Serial.println(pressCount);
}
}
lastButton = currentButton;
delay(20); // hide the bounce
}Step 6 — verify the fix
- Press the button 5 times fast. Count: 5. Every time.
- Press 10 times fast. Count: 10.
- Bang the button. Hold and release. Press extra-hard. The count is always equal to the number of physical presses.
- One physical press = one count. Reliable, predictable, deterministic.
Basic 7 min
Goal: Find the smallest delay() value that still works. Start at delay(2), re-upload, do the five-fast-presses test, and adjust.
delay(____); // experimentTry these values in order, doing the fast-presses test each time:
delay(2)— does it work?delay(5)delay(10)delay(20)delay(50)delay(200)
It works if: you have a written result (count correct or not) for every value, and can name the smallest one that never miscounts.
Questions:
- What's the smallest delay that always gives an accurate count for your specific button? ____
- At what delay value does the button start feeling "sluggish" — like your finger is faster than the Arduino? ____
- Why is the "safe" answer (20–50 ms in textbooks) a bit larger than the absolute minimum you found? (Hint: not every button bounces the same way; the textbook value works for everyone.) ____
Challenge 1 7 min
Goal: A different debouncing pattern — the "two-read confirmation". Instead of slowing the whole loop, you read the pin twice with a short pause between, and only count a change if both reads agree.
1. Think first (on paper, no typing yet):
- You need two readings with a short pause (about 5 ms) between them. What will you call them, and how do you make the Arduino pause?
- Which part of your existing
loop()should only run when the two readings agree? Does the line that remembers the last reading belong inside that part, or outside? Why? - Write your new
loop()as plain-English steps first.
2. Code it. Start from your bounce-bug sketch from Step 1 — the one without delay(20). Change only loop().
3. Upload and observe. Do the five-fast-presses test, several times.
It works if five fast presses give a count of exactly five, and there is no delay(20) at the end of loop().
Questions:
- What condition did you put in your new
if? ____ - What does the delay(5) between the two reads do? Why can it be shorter than the bounce? ____
- If
firstReadandsecondReaddisagree, what does your sketch do? ____ - Compare your version to the simple end-of-loop
delay(20). Does the button feel more or less responsive? ____
Challenge 2 6 min
Goal: A "tap-to-light" reflex game. The onboard LED comes on after a random short pause; the player has to press the button as quickly as possible to turn it off. The Serial Monitor prints how many milliseconds you took.
For the random pause use delay(random(1000, 5000)) — Arduino's built-in random(min, max) returns a random integer between min and max-1.
For the reaction time itself, you'll need millis() — the number of milliseconds since the Arduino started. You haven't met it, or while, formally. Here are two building blocks, just enough to use today:
// Building block 1: remember the time now, work out how long since.
unsigned long start = millis();
unsigned long reactionMs = millis() - start;
// Building block 2: wait here until the button is pressed.
while (digitalRead(BUTTON_PIN) == HIGH) {
}1. Think first (on paper, no typing yet): One round of the game is made of these steps — but they are jumbled. Put them in the right order on paper:
- work out the reaction time
- switch the LED on
- rest for 2 seconds before the next round
- wait for the press
- wait a random time
- switch the LED off and print the time
- remember the time
Then ask: at which exact moment must the clock start? At which moment must it stop? Check your order against both answers.
2. Code it. Start from your bounce-bug sketch: keep the constants and setup(), empty out loop(), and turn your ordered steps into code using the two building blocks.
3. Upload and observe. Open the Serial Monitor and play a few rounds.
It works if the LED lights after a different wait each round, goes off the instant you press, and the Serial Monitor shows a sensible number (a few hundred ms).
You don't need debouncing here because we're only checking the first press, not counting multiple. Bounce just means the LED goes off a millisecond early — too small to matter.
Questions:
- Play 10 rounds with a partner. Whose average reaction time is faster? ____
- For comparison, top sprinters react in about 140 ms. How close did you get? ____
- Where did you put building block 1's two lines? What happens to the times if you swap "remember the time" and "wait for the press"? ____
- The
whileloop spins waiting for the press. Why isn't this a problem (nodelayneeded)? (Hint:whileloops come later, but their job here is just "wait until something changes".)
Challenge 3 15 min
Fix the bouncy toggle
A classmate wrote a toggle: each press flips the onboard LED on or off. They knew about bounce and added a delay(20). It mostly works. But every so often the LED flips back the moment you let go.
const int BUTTON_PIN = 7;
const int LED_PIN = 13;
int lastButton = HIGH;
int ledState = LOW;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int currentButton = digitalRead(BUTTON_PIN);
if (currentButton != lastButton) {
if (currentButton == LOW) {
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
delay(20);
}
}
lastButton = currentButton;
}Your task:
- Type the sketch in exactly and upload it.
- Press and release the button 20 times, quickly. Tally how often the LED changes on the release instead of the press.
- Find the line that is in the wrong place. Write down which bounce it protects against, and which bounce it misses.
- Fix the sketch by moving that one line. Do the 20-press test again.
It works if 20 presses give exactly 20 flips, and the LED never changes as you let go.
Recap 5 min
Mechanical buttons bounce for 3–20 ms after every press, sending a brief burst of state changes that the state-change pattern from L01-19 will faithfully count. The simplest fix is one extra line: delay(20) at the end of loop(). It slows the loop just enough that the bounce has settled by the next read. From now on, every Arduino sketch you write with a button will include this line.
- Bounce / contact bounce
- The rapid open-and-close oscillation that happens at a mechanical switch's contacts immediately after they touch. Lasts roughly 3–20 ms.
- Debouncing
- Any technique that hides bounce from the rest of the sketch, so that one physical press = one detected event. The simplest technique is a short
delayat the end ofloop(). - Settled state
- The level of a signal after the bounce region has finished. The signal we actually care about.
- Blocking vs non-blocking
- A
delay()is blocking — nothing else can happen during it. Later in Level 2, you'll learn themillis()pattern that "remembers when something happened" without blocking, so multiple things can run at once. For Level 1, blocking is fine. - Deterministic
- A program is deterministic if it always produces the same result for the same input. Buttons without debouncing are not deterministic — same physical press might count as 1 or 2 or 3. Adding the delay makes the behaviour deterministic again.
Extra Mission 5 min
Part 1 — Design a counter that must never miscount
Some counters really matter. A lap counter at a race. A tally of people entering a school hall. A score button in a game. Pick one. On paper, design a button-press counter for it.
Your design must include:
- What is being counted, and who presses the button.
- What goes wrong for real people if bounce adds extra counts.
- A target number, and what the device does when the count reaches it.
- What the LED and the Serial Monitor show after every press.
Part 2 — Make it
Build your counter with today's button on D7 (INPUT_PULLUP) and the onboard LED. Start from the fixed sketch in Step 5.
- Add a
const int TARGETwith your target number. - Print the count to the Serial Monitor after every press.
- When
pressCount == TARGET, turn the LED on. - Keep the
delay(20)debounce at the very end ofloop().
Test it with fast presses. The LED must light on exactly the target press — never early.
Bring back next class: your design, the saved .ino file, and a screenshot of the Serial Monitor counting up to your target.