A button is the simplest way to talk to a circuit. But if you build a counter that increments with each press, you may find it goes up 3 or 4 times per press! Let's look at the types, that problem, and how to fix it in code and in hardware.
The types
- Momentary (push button): on only while you hold it down, like a doorbell button.
- Toggle: stays in the position you leave it, like a light switch.
- Latching: one press turns on and the next turns off, like the power button on many devices.
- Micro switch (limit switch): a button with a lever, pressed when something reaches the end of its travel, like a microwave door or the end stops on a 3D printer.
- NO and NC: NO is open at rest and closes when pressed; NC is the opposite. A micro switch usually has both, with a common terminal (COM), like a relay.
The tactile switch (4 legs)
The small square button we use on a breadboard has 4 legs, but it's one switch: each pair of facing legs is always connected inside, and pressing connects the two pairs together. The safest approach is to use two legs diagonally opposite each other, so you can't pick two legs that are already connected. If in doubt, use continuity mode on a multimeter.
Connecting it to a microcontroller
An unconnected pin "floats" and reads random values, so the button needs a pull-up or pull-down. The easiest is to use the pull-up inside the chip:
pinMode(2, INPUT_PULLUP); // with the button between the pin and ground
// pressed = LOW, not pressed = HIGH
This needs no external resistor, and the inverted logic (pressed = LOW) is what confuses many people at first.
The bounce problem
When the metal contact closes, it strikes and rebounds several times in the first few milliseconds before it settles. A person doesn't notice, but a microcontroller is very fast: an Arduino runs loop thousands of times per millisecond, so it sees each rebound as a separate press.
Bouncing happens on release as well as on press, and its duration varies from switch to switch: small new buttons are usually under 5 ms, while large or old buttons and toggle switches can reach 20 ms or more.
The fix in code
The idea: when you see a change, wait a little and confirm it's stable. This code counts presses correctly:
const int BTN = 2;
const unsigned long DEBOUNCE = 30; // milliseconds
bool lastStable = HIGH, lastRead = HIGH;
unsigned long changedAt = 0;
int count = 0;
void setup() {
pinMode(BTN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
bool r = digitalRead(BTN);
if (r != lastRead) { changedAt = millis(); lastRead = r; }
if (millis() - changedAt > DEBOUNCE && r != lastStable) {
lastStable = r;
if (lastStable == LOW) { // one real press
count++;
Serial.println(count);
}
}
}
20–50 ms is enough for most buttons. And notice the code doesn't stop the program: the rest of loop runs normally, which is the difference from delay(). The idea is explained in detail in the millis instead of delay article.
Try the difference yourself
Remove the DEBOUNCE condition from the code (set it to 0) and press the button 10 times. The counter will probably pass 10. Set it back to 30 and it counts correctly. Open the Serial Monitor to see the numbers.
The long press
With the same idea you can tell a short press from a long one: record the time the moment the button is pressed (after debouncing), and when it's released, calculate the duration:
unsigned long pressedAt = 0;
// inside the condition above:
if (lastStable == LOW) pressedAt = millis();
else {
unsigned long held = millis() - pressedAt;
if (held > 800) Serial.println("long press");
else Serial.println("short press");
}
That way one button does two jobs, like a clock button that changes mode with a long press and increments the number with a short one.
More than one button
If you have 3 or 4 buttons, don't duplicate the variables by hand: put them in arrays and loop over them with for, or use a ready-made library such as Bounce2 or OneButton (the latter has long presses and double presses built in). And if you have lots of buttons, a keypad saves pins.
Several buttons on one analog pin
If you run out of pins, you can put 4 or 5 buttons on a single analog pin: each button connects the pin to a different point in a chain of resistors, so each one gives a different voltage you read with analogRead. For example: a 10 kΩ pull-up, and each button to ground through a different resistor (0, 1 kΩ, 3.3 kΩ, 10 kΩ), so the readings are about 0, 93, 254 and 512 on the 1023 scale. Leave a margin between the values, and debounce the reading too. The drawback is that you can't tell when two buttons are pressed together. This idea is exactly a voltage divider, and reading it is covered in the ADC article.
The fix in hardware
A 10 kΩ resistor and a 100 nF capacitor make an RC time constant of about 1 ms that smooths the bounce. The capacitor discharges instantly when you press, and charges slowly through the resistor when you release, so the small rebounds can't change its voltage much.
The catch is that the voltage on the capacitor rises slowly, and an ordinary microcontroller pin can get confused while it's halfway. That's why a Schmitt trigger chip (such as the 74HC14) goes after them: it has different thresholds for rising and falling, so it outputs one clean edge. Note that the 74HC14 inverts the signal, so pressed becomes HIGH at the microcontroller.
This fix is useful if the button triggers an interrupt, or in circuits with no microcontroller at all (such as a button that triggers a 555 timer or a counter).
Code or hardware?
| Debouncing in code | Debouncing in hardware | |
|---|---|---|
| Cost | Nothing | A resistor, capacitor and chip |
| Changing it | A number in the code | Changing parts |
| With interrupts | Needs care | Comfortable |
| Without a microcontroller | Impossible | The only option |
In most Arduino projects, code is enough. Hardware is for when the code isn't in your hands, or the button is far away and picks up noise.
Tips
- Don't use a long
delay()for debouncing, because it stops the rest of the program. - Cheap or old buttons bounce more. If it still miscounts, increase the time.
- Long wires to buttons pick up noise: use a stronger pull-up (say 4.7 kΩ) and a small capacitor.
- Buttons that people touch outside the enclosure can pass static to the pin, so a small series resistor (100 Ω to 1 kΩ) protects the chip. Details are in the ESD article.
- If you want a button with no moving parts at all, there are touch buttons.
FAQ
Why does the button read pressed by itself without me touching it? The pin is floating: you forgot INPUT_PULLUP or the resistor. Or the button is fitted on two legs that are always connected.
Can I use a pull-down instead of a pull-up? Yes, with an external 10 kΩ resistor to ground and the button to the supply, and pressed becomes HIGH. But the Uno has no internal pull-down, so a pull-up is easier.