Turn button presses into a number.
This lesson combines everything so far. The button is the input, a variable stores the count, and the Serial Monitor lets you see the value change. The key new idea is detecting a press once, rather than counting continuously while the button is held.
Use the tactile-button circuit
Keep the tactile button connected between digital pin 2 and GND, using INPUT_PULLUP. The LED may stay on pin 8 for the final challenge.
Goal: each physical press increases a stored number by exactly one.
Why the obvious method fails
If you write if (buttonState == LOW) count++;, the UNO can execute that line thousands of times while your finger is still holding the button. We need to count only the moment the signal changes from HIGH to LOW.
The complete counter
const int buttonPin = 2;
int count = 0;
int lastButtonState = HIGH;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int buttonState = digitalRead(buttonPin);
if (buttonState == LOW && lastButtonState == HIGH) {
count = count + 1;
Serial.println(count);
delay(30);
}
lastButtonState = buttonState;
}Open the Serial Monitor at 9600 baud. Each clean press should print 1, 2, 3, 4 and so on.
Follow the logic
Read the button. The current value goes into buttonState.
Compare current and previous. LOW now plus HIGH before means a new press has just started.
Add one. count = count + 1; stores the new total.
Remember the state. At the end of the loop, the current reading becomes the previous reading for next time.
About button bounce
Mechanical contacts can rapidly make and break contact for a few milliseconds when pressed. The short delay(30) is a simple beginner-friendly debounce. Later in the course we can replace blocking delays with a proper millis()-based debounce.
Experiments
- Change the code so each press adds 2 instead of 1.
- Add a second button that resets
countto zero. - Use the LED on pin 8 so it turns on when the count reaches 5.
- Make the counter wrap back to zero after 10.
Final challenge for this stage
Build a five-press trigger: the LED is off when the program starts. Each press increases the count. On the fifth press, turn the LED on and reset the counter to zero. Do this without copying a finished solution.