Button Counting and Toggling

This activity will explore the many features of the Arduino example sketch State Change Detection.

To start load and state change detection sketch to the Arduino and build the Button and LED circuits.

Open the serial monitor and operate the button to observe the sketches function.

Question Describe the output from this sketch ( what happens when the button is pushed or released).

const int buttonPin = 2; // the pin that the pushbutton is attached to

const int ledPin = 13; // the pin that the LED is attached to

// Variables will change:

int buttonPushCounter = 0; // counter for the number of button presses

int buttonState = 0; // current state of the button

int lastButtonState = 0; // previous state of the button

The first thing to notice about this sketch is the use of variables, the circuit uses a single button but the sketch uses 4 variables related to the same button:

What are the 4 varialbes related to the button?

What information about the button does each hold?

if (buttonState != lastButtonState)

The first if statement checks to see if the button has been pushed or released.

The comparison used if != what does this mean?

if (buttonState != lastButtonState) {

// if the state has changed, increment the counter

if (buttonState == HIGH) {

The second if statement is indented to show that this only happens if the first if statement is true.

What does the second IF statement check?


This statement can also be written buttonPushCounter=buttonPushCounter + 1;

It means add 1 to the value stored in the variable called buttonPushCounter

if (buttonPushCounter % 4 == 0) {

digitalWrite(ledPin, HIGH);

} else {

digitalWrite(ledPin, LOW);


The last if statement toggles the led on and off each forth push of the button.

Try changing the number in the test equation.

What is the effect?

What does the % mean, what other name do you know this math operation by?

(check the Arduino reference for the answer to this question)

Include a Fritzing Diagram of you circuit?

Take and photo of your Completed circuit.

Take a Screen capture of your serial monitor output showing all possible conditions.

(alt print screen will place a screen capture of the active window on your clipboard that you can paste into your document )

Answer the above Questions on the assignment sheet.