Counting Presses

The following text and code examples were copied and slightly modified from under as such, this page is subject to the same license.

A pretty useful techinque you'll want to add to your collection of sketch-knowledge is how to keep track of button presses. Try this sketch:

 *  Counting presses

int switchPin = 2;              // switch is connected to pin 2
int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int buttonPresses = 0;          // how many times the button has been pressed

void setup() {
  pinMode(switchPin, INPUT);    // Set the switch pin as input
  Serial.begin(9600);           // Set up serial communication at 9600bps
  buttonState = digitalRead(switchPin);   // read the initial state

void loop(){
  val = digitalRead(switchPin);      // read input value and store it in val
  if (val != buttonState) {          // the button state has changed!
    if (val == LOW) {                // check if the button is pressed
      buttonPresses++;               // increment the buttonPresses variable
      Serial.print("Button has been pressed ");
      Serial.println(" times");
  buttonState = val;                 // save the new state in our variable

Notice, we've added the ++ operator. Simply, the statement "buttonPresses++" increments (adds 1 to) the buttonPresses variable. This is a shortcut for "buttonPresses = buttonPresses + 1". We first saw this in the For Lesson from Unit 4.

Additional Tasks:
  1. Modify this sketch so that it increments the variable when you let go of the button rather than press it.
  2. Change this sketch so that it counts down rather than up. When you get to zero you should reset the variable so you can start over.
  3. Attach 5 LEDs to your Arduino. At the beginning of the program they should all be turned on. Each time I push the button, one should go out.