Buttons, pull-up resistors and debouncing
Why a button needs a pull-up or pull-down resistor, how active-low logic works, and how to turn a bouncing mechanical contact into one clean press in software.
Lesson 3 of 6 · 30 min · Self-paced · Free
A button is harder than it looks
A button seems like the easiest input there is: pressed or not pressed. Yet two problems catch out almost every beginner. First, a button wired to a pin with nothing else often reads random values. Second, a single press can be counted as three, five or ten presses. On a robot, that might mean an emergency-stop reset that triggers twice, or a mode button that skips straight past the mode you wanted. This lesson fixes both problems: the first with a resistor, the second with a few lines of careful code.
Problem one: the floating input
Wire a button between a pin and ground. When pressed, it connects the pin to 0 V, which reads as 0. But when released, the pin is connected to nothing. As you saw in the previous lesson, a floating input can read 0 or 1 unpredictably.
The fix is a pull-up resistor: a resistor from the pin to the supply voltage.
- Released: the input pin draws almost no current, so there is almost no voltage across the resistor (V = I × R with I ≈ 0). The pin sits at the supply voltage and reads 1.
- Pressed: the button connects the pin straight to ground, so it reads 0. Current now flows from the supply, through the resistor and the button, to ground.
Notice the logic is reversed: pressed means 0. This is called active-low, and it is extremely common. Your code just needs to know which way round it is.
How big should the resistor be?
With a 10 kΩ pull-up on a 3.3 V supply, the current while the button is pressed is:
I = 3.3 V / 10 000 Ω = 0.00033 A = 0.33 mAThat is tiny and wastes little energy. Compare the extremes:
- Too small, say 0 Ω (a plain wire): pressing the button would short the supply to ground.
- Too large, say 10 MΩ: the pull is so weak that tiny leakage currents and electrical noise can drag the pin below the threshold.
Values from a few kilohms to about 100 kΩ are typical, and 10 kΩ is a popular choice. A pull-down resistor is the mirror image: a resistor to ground and a button to the supply, giving active-high logic.
Most microcontrollers also contain internal pull-up resistors, often tens of kilohms, which you switch on in software when you configure the pin, for example with an illustrative mode such as GPIO_INPUT_PULLUP. That saves a component, though the datasheet will tell you the exact value range, which may be wide.
Problem two: contact bounce
Inside a button, two metal contacts snap together. They do not settle instantly. They hit, spring apart, hit again, and chatter for a short time, often a few milliseconds, sometimes longer for worn or cheap switches. A microcontroller reading the pin thousands of times per second sees this chatter as a burst of separate presses. This is contact bounce.
A pin sampled every millisecond might see something like this during a single press and release (1 = released, 0 = pressed):
1 1 1 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 1 1Count the changes from 1 to 0: there are five, but the person pressed only once.
Fixing bounce
There are two broad approaches.
Hardware debouncing adds a resistor and capacitor (an RC filter) so the voltage cannot change instantly, often followed by a Schmitt trigger input, which has two thresholds so a slowly changing voltage produces one clean edge.
Software debouncing accepts a new level only after it has stayed the same for a set time. This costs no parts, so it is very common. Here is a complete, portable C version you can compile and run on any computer. It feeds in the made-up samples above, one per millisecond.
#include <stdio.h>
#include <stdint.h>
#define STABLE_MS 5 /* real buttons: use 10 to 20 */
typedef struct {
int stable; /* debounced level: 1 = released, 0 = pressed */
int last_raw; /* the previous raw sample */
uint32_t count; /* how many ms the raw level has stayed the same */
} Debouncer;
/* Call once per millisecond with the raw pin level.
Returns 1 exactly once per press. */
int debounce_update(Debouncer *d, int raw) {
if (raw == d->last_raw) {
if (d->count < STABLE_MS) d->count++;
} else {
d->last_raw = raw;
d->count = 0;
}
if (d->count >= STABLE_MS && raw != d->stable) {
d->stable = raw;
return raw == 0; /* report only the press, not the release */
}
return 0;
}
int main(void) {
/* Made-up samples, one per ms: a press that bounces, then a
release that bounces. 1 = released, 0 = pressed. */
int raw[] = {1,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,
1,0,1,1,0,1,1,1,1,1,1,1,1,1};
int n = sizeof raw / sizeof raw[0];
Debouncer d = {1, 1, STABLE_MS};
int raw_presses = 0, presses = 0;
for (int i = 0; i < n; i++) {
if (i > 0 && raw[i - 1] == 1 && raw[i] == 0) raw_presses++;
if (debounce_update(&d, raw[i])) {
presses++;
printf("press detected at t = %d ms\n", i);
}
}
printf("raw falling edges: %d, debounced presses: %d\n", raw_presses, presses);
return 0;
}Compile and run it with cc -std=c99 -Wall debounce.c -o debounce and then ./debounce. The output is:
press detected at t = 13 ms
raw falling edges: 5, debounced presses: 1The last bounce happens at t = 8 ms. The level then stays at 0 for five more samples, so the press is confirmed at 13 ms. The release bounces too, but the function deliberately reports only presses.
Two design points are worth noticing. First, the function reports an edge, the moment of change, not a level. "Do something once per press" needs edges; "keep the motor running while held" needs the level. Second, the logic does not touch any hardware: it takes a number in and returns a number. That is why you can test it on a laptop with made-up data before it ever runs on a chip. On a real board you would call it once per millisecond with gpio_read(BUTTON_PIN).
The delay costs you a few milliseconds of response time, which no human will notice. Choosing the stable time is a trade-off: too short and bounce gets through; too long and quick double-presses get merged.
Recap
An input needs a defined level at all times: a pull-up resistor (external or internal) holds it high, and the button pulls it low, giving active-low logic. Mechanical contacts bounce, so one press can look like many. Debounce in hardware with an RC filter and Schmitt trigger, or in software by accepting a level only after it has been stable for a set time. Act on edges for one-off actions and on levels for held actions.
Project
Experiment with the debouncer
Copy the debouncer program above into a file, compile it with cc -std=c99 -Wall and run it. Then experiment:
- Change
STABLE_MSto 2. Predict how many presses will be detected, then run it and explain the result. - Change it to 12. What happens now, and why?
- Edit
debounce_updateso it also reports releases (for example by returning 2 for a release). Print both events. - Write your own bouncing sample array for a double press, two quick presses about 40 ms apart, and check that your chosen
STABLE_MSseparates them.
This is a software-only activity: no hardware is needed.
Deliverables
- Your predictions and actual outputs for STABLE_MS = 2 and 12, with explanations
- The modified function that reports releases
- Your double-press test data and its output
Knowledge check
Check your understanding
Go further
- Pull-up resistor (Wikipedia) ↗
How pull-up and pull-down resistors define logic levels, with circuit examples.
- Switch: contact bounce (Wikipedia) ↗
The section on contact bounce and common ways of dealing with it.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.