Push Button Experiments

After completing the Push Button project, test yourself by trying these experiments.

1 Very often we need to make connections similar to the one used for the push button where an external resistor is needed as shown here. Push button schematic
To simplify the connections, an internal pull-down resistor (i.e. the resistor is connected to GND) is built-in to each of the digital pins on the Arduino so that an external resistor is not needed. Built-in pull-down resistor

To use the internal pull-down resistor, set the pinMode command to OUTPUT but use it for input.
Built-in pull-down resistor
Remove the external 22K ohm resistor and the wire that connects the resistor to GND on the breadboard, and then run your modified program.
You should get the same result.
2 Instead of using the push button to control the internal LED connected to pin 13, make the push button to control an external LED that is connected to pin 3.

Do not change the push button connections. Just add the connections for an external LED like the picture on the right.

Next, modify the code to control the external LED instead of the internal LED. Hint: change pin 13 to pin 3 in the code.
External LED connection
3 Add a buzzer to what you have from experiment 3. Make it so that when you press the push button the external LED will turn on and the buzzer will sound one note, and when you release the button both of them will turn off.

The if command checks the buttonState variable to see if it is HIGH or LOW. The double-equal sign == is used to test for equality. If buttonState is equal to HIGH then the first digitalWrite command is executed to turn on the LED and then the tone command is executed to sound the buzzer,

otherwise the second digitalWrite command in the else part of the if command is executed to turn off the LED followed by the noTone command to turn off the buzzer.

Notice the use of the open and close braces to bracket the body of the true and false parts of the if command.
4 Create an electronic dice using the push button and the 7-segment LED display. Roll the die by pressing the button. The 7-segment LED display will display a random number between 1 and 6.
Optional advance stuff
5 Write a program to count how many times a push button is pressed.
int pushButton = 2;
int led = 13;

// function to count number of button presses
int countButtonPresses() {
  static int count = 0;
  // wait for button press
  digitalWrite(led, LOW);
  while (digitalRead(pushButton) == LOW) {

  // button has been pressed
  digitalWrite(led, HIGH);
  // wait for button release
  while (digitalRead(pushButton) == HIGH) {
  return count;

void setup() {
  pinMode(pushButton, OUTPUT);  // for input using internal pull-down resistor
  pinMode(led, OUTPUT);

void loop() {