Count Button Presses
Part of the Inputs section of Coddy's Arduino journey. Lesson 5 of 22.
The edge from the last lesson can drive anything that should happen once per press. Here it adds one to a counter, with ++ from Counting Up:
int presses = 0;
void loop() {
int reading = digitalRead(2);
if (reading == LOW && lastReading == HIGH) {
presses++;
Serial.println(presses);
}
lastReading = reading;
}presses sits above setup(), like lastReading, so it keeps its value between runs of loop().
The print is inside the if, so a number appears only when the count changes: 1, 2, 3. Outside the if it would print the same count thousands of times a second.
Challenge
EasyThe button is on pin 2 (INPUT_PULLUP). Count its presses:
- keep the count in
presses, declared abovesetup() - when the button goes down, add one and print the count
Press Run, press the button a few times and watch the Serial monitor, then Check.
Try it yourself
const int buttonPin = 2;
int lastReading = HIGH;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int reading = digitalRead(buttonPin);
// when the button goes down, count it and print the count
lastReading = reading;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Inputs
Practice on your own: Arduino playground