Use a Push Button Switch with Arduino | Starting Electronics

Use a Push Button Switch with Arduino

Created on: 19 January 2022

Use a push button switch with Arduino in this part of the Arduino tutorial for beginners. Example sketch code reads the switch or button state to determine whether the switch is open or closed. Connect a push button switch to an Arduino Uno or MEGA 2560 in this part of the tutorial. Afterwards, load a sketch that reads the state of the switch. Push the push button switch and the sketch code on the Arduino switches an LED on in response. Also send text to the Arduino IDE serial monitor window that shows when the push button switch is open or closed.

Part 8 of the Arduino Tutorial for Beginners

A push button switch called a momentary push button switch is used in this tutorial. Momentary means that the switch stays closed only while pushed. When the switch is released, the contacts open. The image below shows examples of this type of switch. Use a wire link instead if you do not have a push button switch. Connect the wire link to the breadboard circuit to simulate closing the switch, and disconnect the wire link to simulate opening the switch.

Momentary push button switches
Momentary Push Button Switches

How to Connect a Push Button Switch to an Arduino

There is more than one way to connect a push button switch to an Arduino. In this tutorial, a pull-down resistor is used in conjunction with the push button switch. Pull-down describes the function of the resistor in the circuit, it is not a special type of resistor. In fact a 10k resistor is used in the circuit. Although a 10k resistor is specified, any resistor from around 4k7 to 20k works in the circuit.

For more information on pull-up resistors, pull-down resistors, and other Arduino input pin configurations, see the Ultimate Arduino Uno Hardware Manual for Arduino Uno boards. Find the same information for Arduino MEGA 2560 boards in the Ultimate Arduino MEGA 2560 Hardware Manual.

Get a 10k Resistor

A 10k resistor has a value of 10,000 ohms. The letter k in 10k is short for kilo which means 1000. A 5% tolerance 10k resistor has the colors brown, black and orange, as shown in the image below.

10k Resistor Colors and Values
10k Resistor Colors and Values

As the above image shows, the resistor brown band has a value of 1 and black a value of 0. This means that the resistor value starts with 10. Orange has a value of 3, which means three zeros. Put the three zeros after the first two digits and we get 10,000 or 10k. Refer back to part 6 of this tutorial, Build a Breadboard Circuit for Beginners, for more information on reading resistor values.

Get a Momentary Push Button Switch

Get a momentary push button switch ready to plug into the breadboard circuit. As can be seen in the following image, pins opposite each other on a push button switch are connected. The push button switch on the left shows the orientation of the push button, which is the orientation of both push buttons in the image. On the right, the switch shows the internal connections of the pins.

Push Button Switch Internal Wiring
Push Button Switch Internal Wiring

As can be seen in the image, opposite pins are electrically connected and essentially one piece of metal. When the button is pushed, the metal strips electrically join together. Release the button and the connection is broken again.

Put your multimeter onto the continuity setting. See the article on basic continuity testing with a multimeter. Test the switch by checking that the opposite pins are one continuous metal conductor. First plug the switch into a breadboard to make it easier to use the multimeter probes on the switch pins. Test the functionality of the switch with the multimeter afterwards. In other words, test between pins on the same side of the switch to verify that they are open circuit. Afterwards, push the button to verify that the pins are now electrically joined.

Arduino Push Button Switch Breadboard Circuit

The following sub-sections show how to connect a push button switch to an Arduino Uno and then an Arduino MEGA 2560 using a breadboard circuit.

Connect a Push Button Switch to an Arduino Uno

The following image shows how to connect a push button switch to an Arduino Uno using a pull-down resistor. Firstly, plug the push button switch into the breadboard so that it straddles the middle channel. Secondly, plug the 10k resistor into the breadboard as shown in the image. In order to do this, bend the leads or legs of the resistor down first. Finally, connect the breadboard circuit to the Arduino with Dupont wires or similar jumpers. Connect Arduino digital pin 2 to the push button switch as the green wire shows in the image. Next, connect a GND pin to the free end of the 10k resistor as the black wire shows in the image. Lastly, connect the 5V Arduino pin to a push button pin as the red wire shows in the image.

Arduino Uno Push Button Switch Breadboard Circuit
Arduino Uno Push Button Switch Breadboard Circuit

Black wires are used to represent GND or 0V in a circuit, as was mentioned in a previous part of this tutorial. In addition, red wires are used to represent positive voltages by convention. In the above example, a red wire is used for the positive 5V connection. Again, this is by convention and any color wire can be used instead if a red wire is not available.

Connect a Push Button Switch to an Arduino MEGA 2560

The following image shows an equivalent push button circuit for an Arduino MEGA 2560 board. To avoid using a long wire from the 5V pin at the bottom left of the board, 5V is taken from the top right of the board instead. 5V from the top right of the board is first connected to the positive horizontal rail of the breadboard. Afterwards, a jumper link joins the positive rail to the switch. Alternatively a single wire can be used to connect directly from 5V to the switch.

Arduino MEGA 2560 Push Button Switch Breadboard Circuit
Arduino MEGA 2560 Push Button Switch Breadboard Circuit

Different Ways to Build the Same Breadboard Circuit

As was already mentioned in a previous part of this tutorial on how to build a breadboard circuit for beginners, there are many ways to build the same circuit on a breadboard. For example, the same circuits above are built differently in the Button example from Arduino. In the breadboard circuit on that page, Arduino 5V and GND are first taken to the horizontal + and – rails of the breadboard. Afterwards, these voltages are connected from the rails to the switch and resistor using separate jumpers.

Arduino Push Button Switch Circuit Diagram

The following image is a circuit diagram of the previous two breadboard circuits. R1 is a 10k resistor that pulls Arduino pin 2 to GND. With the switch S1 open, a voltage level of 0V is read on pin 2 by the Arduino. When the switch is closed, 5V is attached to pin 2 of the Arduino. In this case, the Arduino sees 5V on pin 2. A sketch reads 0V and 5V on a digital pin as 0 and 1 logic levels. An article on the basics of switches for beginners shows different symbols used for switches in circuit diagrams.

Arduino Uno and MEGA 2560 Push Button Switch and Pull-down Resistor Circuit
Arduino Uno and MEGA 2560 Push Button Switch and Pull-down Resistor Circuit

Below is an alternate circuit diagram that is electrically equivalent to the above circuit, but drawn differently.

Alternate Push Button Switch Circuit for Arduino Uno or MEGA 2560
Alternate Push Button Switch Circuit for Arduino Uno or MEGA 2560

Read Switch State with Arduino and Switch an LED

Use the previous circuit with an Arduino Uno or Arduino MEGA 2560 and the Button example sketch. Open the Arduino IDE and select File → Examples → 02.Digital → Button from the top menu bar. This opens the Arduino Button sketch from the built in examples. After building the circuit shown in the previous section, upload the Button example sketch to the target Arduino board. After uploading the sketch, press the push button switch on the breadboard to close the switch. The on-board LED switches on when the push button switch is closed, and switches off when the push button switch is released, or opened.

Code from the Button sketch is listed below for reference.

/*
  Button

  Turns on and off a light emitting diode(LED) connected to digital pin 13,
  when pressing a pushbutton attached to pin 2.

  The circuit:
  - LED attached from pin 13 to ground through 220 ohm resistor
  - pushbutton attached to pin 2 from +5V
  - 10K resistor attached to pin 2 from ground

  - Note: on most Arduinos there is already an LED on the board
    attached to pin 13.

  created 2005
  by DojoDave <http://www.0j0.org>
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/Button
*/

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

How the Arduino Button Example Sketch Works

The Button sketch is broken up into parts and placed under various sub-headings that follow. Each part of the sketch is explained under the sub-headings.

Constant Integers

At the beginning of the Button sketch, two constant integers are defined, as shown in the following image.

Constant integers at start of the Arduino Button example sketch

In the above code, the keyword const means constant, and int means integer. What the above two lines of code do is define two constant values called buttonPin and ledPin. Both constant values are integers, which means that they have to be assigned values that are whole numbers and not fractions. Constant buttonPin is assigned a value of 2 and ledPin is assigned a value of 13. Wherever the name buttonPin is used in the sketch, 2 is placed. Wherever ledPin is used, 13 is placed. This just gives the push button switch on pin 2 and the built-in LED on pin 13 meaningful names.

Using buttonPin to reference pin 2 that has the button attached to it makes the code in the sketch easier to understand. Likewise, ledPin is used in the sketch to refer to the pin that the LED is attached to instead of the pin number, which is 13.

Integer Variable

The int keyword on its own, without const, declares an integer variable, as the following image shows.

Arduino integer variable

Integer variables are used in a sketch to hold a value that can change while the sketch is running. Because the state of the push button (open or closed) changes while the sketch is running, its state is saved to the buttonState integer variable. The above line of code defines an integer variable called buttonState and assigns it an initial value of 0. Later in the sketch, when the state of the switch on pin 2 is read, it will have a value of 0 if open, and 1 if closed. This value is put into the buttonState variable so that it can be tested to see whether the switch is open or closed.

Button Sketch setup() Function Code

Two hardware items are used in the Button example sketch. These are the push-button switch and the on-board LED. As a result, these two items are set up in the setup() function of the Arduino Button sketch, as the following image shows.

Button sketch setup() function code

In the above code, the pinMode() function is called twice. The first time it is called, it sets up the on-board LED pin as an output pin. It is passed the constant integer ledPin which resolves to 13. This is because ledPin is the constant integer defined at the start of the sketch. After this, OUTPUT is passed to the function which sets the selected pin up as an OUTPUT, able to drive or switch the attached LED.

The second call to pinMode() is passed the constant integer buttonPin, which resolves to 2. In addition to this, the second value passed to pinMode() is INPUT. This sets up pin 2 as an input pin, able to read the logic levels of 1 and 0 on the pin, to determine whether the attached switch is closed or open.

Button Example Sketch loop() Function

The remaining code of the Button example sketch is found in the loop() function, as the following image shows.

Button sketch loop function
Get the State of the Push Button Switch

At the start of the loop() function, a function called digitalRead() is called. It is passed the constant integer buttonPin, which resolves to 2. In other words, digitalRead() reads the current state of the switch attached to digital pin 2. This is possible because digital pin 2, defined as buttonPin was set up as an input in the setup() part of the sketch. The digitalRead() function returns a value of 0 (also called LOW), or 1 (also called HIGH), depending on whether the attached switch is open or closed. The value returned is assigned to the buttonState variable. This is done using the = assignment operator. In short, this line of code gets the state of the switch and puts it in the buttonState variable.

Determine if the Switch is Open or Closed

An if-else construct follows. The purpose of this construct is to determine whether the switch is open or closed. In other words, whether the buttonState variable contains a value of HIGH or LOW.

// if-else construct
if () {    // If this evaluates to true
           //  then run code in this block
} else {
           // Otherwise run code in this block  
}

In the parentheses that follow the if keyword is a test that checks whether buttonState contains a value of HIGH. The double equals sign == is the equal-to operator. (buttonState == HIGH) means: Does the variable buttonState contain the value HIGH? If buttonState does contain HIGH, the expression (buttonState == HIGH) is said to have evaluated to true. In this case, the code between the braces that follows the if statement is run, switching the LED on. This only occurs if the switch is closed.

When the switch is open, the if statement evaluates to false because buttonState does not contain HIGH. Instead, it contains LOW. This causes the code between the braces that follow the else keyword to run instead. The code between the braces switches the on-board LED off.

The following code contains comments that explain what the code does.

if (buttonState == HIGH) {     // If the switch is closed (or if buttonState contains the value HIGH)
  digitalWrite(ledPin, HIGH);  // Turn the LED on
} else {                       // If the switch is not closed (it is open, or buttonState contains the value LOW)
  digitalWrite(ledPin, LOW);   // Turn the LED off
}

Send the Switch State to the Serial Monitor

The DigitalReadSerial example sketch sends the state of the switch out of the Arduino USB port. When the switch is open, the sketch continually sends a 0 out of the USB port. On the other hand, when the switch is closed, it sends a 1 out of the USB port. Open the serial monitor window, and the value sent is displayed.

Upload the DigitalReadSerial Example Sketch

In the Arduino IDE, select File → Examples → 01.Basics → DigitalReadSerial from the top menu bar. This opens the DigitalReadSerial example sketch. Upload the sketch to the target Arduino board. After uploading the sketch to the Arduino board, the TX LED appears to be on. The reason for this is that the TX or transmit LED indicates that the Arduino is transmitting on the USB port. The data that is transmitted is the state of the switch.

Open the serial monitor window from the Arduino IDE to see the state of the switch that is sent from the Arduino. Refer back to Arduino Serial Monitor for Beginners, which is part 4 of this tutorial for an explanation of how to use the serial monitor. After the serial monitor opens, a lot of 0 characters are seen scrolling up the window. Press the push button that is attached to pin 2 of the Arduino. This results in the character seen in the serial monitor window changing from 0 to 1. Release the switch, and the value in the serial monitor window changes back to 0.

How the DigitalReadSerial Example Sketch Works

Code from the DigitalReadSerial example sketch follows in the listing below. There is also a DigitalReadSerial Arduino page on the Arduino website.

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1);        // delay in between reads for stability
}

As with the previous Button sketch, pin 2 is given a name. This time it is called pushButton, and defined at the top of the sketch code. In this example it is defined as an integer variable, rather than a constant integer. It is better to define this type of value as a constant, as the pin number that the switch is attached to does not change in the sketch.

In the setup() part of the sketch, pinMode() is used to set pin 2 up as an input again, as was done in the Button sketch. In addition to setting up the pin, the serial port is set up by calling the Serial.begin() function or method. This function is passed a value of 9600, which sets up communications over the serial/USB port at 9600 baud.

In the loop() function of the sketch, the state of the button is read again, as before. The difference is that the integer variable buttonState is defined in the loop() function and assigned the return value of digitalRead() in the same line.

Finally, Serial.println() is called, followed by the delay() function. Serial.println() is a function that sends a value out of the serial/USB port. This function is passed the buttonState variable which contains 0 when the switch is open, or 1 when the switch is closed. The delay() function is passed a value of 1 to generate a 1ms delay between each pass through the loop.

Digital Inputs and Outputs

As this part of the Arduino tutorial for beginner shows, a digital pin can be set up as an input or an output. An example of an output is a pin that drives or switches an LED. Digital inputs are able to read the logic state of a pin. Both sketches in this part of the tutorial determine if a switch is open or closed by reading the logic state applied to a digital input pin.

A logic high state is referred to as HIGH or 1 in an Arduino sketch. It represents a high logic level which is 5V when using an Arduino Uno or Arduino MEGA 2560. A logic low state is referred to as LOW or 0. Logic low is represented by 0V (zero volts) or GND on any Arduino board.