Posts about... All (17) Android (2) Hooking Up Parts (10) Game Controllers (3) Robots (2)

How to Hook Up > Buttons

A button is a simple switch with 2 values: on or off, which is 1 or 0 respectively. No surprise there. This post details how to hook it up and read its value into your Arduino program.

Parts

Steps

  1. A typical button has 4 leads. Place the button on your breadboard. To prevent a short, make sure the 2 sides without leads are over the bridge on your breadboard.
  2. Now choose 1 side (2 leads) of the button to work with. Pick 1 lead to be positive and the other to be negative.
  3. Place a (red) wire from a 5V pin on your Arduino to the positive lead of your button.
  4. Place a (yellow) wire from a digital pin on your Arduino to the ground lead of your button. Leave room for a resistor.
  5. Place one end of a (330 ohm) resistor on your breadboard in between the ground lead of your button and the (yellow) wire to a digital pin. Place the other end of the resistor a few rows down on your breadboard.
  6. Place a (black) wire from the open end of the resistor to a ground pin on your Arduino.
  7. Button

  8. Connect the Arduino to your computer with the USB cable (A to B).
  9. Upload the code below to your Arduino. Once done, open up the Serial Monitor within the Arduino software. The code prints either a 0 or a 1 every 0.1 seconds to state whether the button is pressed or not.

Code

int btn = 4; // a variable for the button's digital pin

void setup()
{
Serial.begin(9600); // start reading values from the serial port
pinMode(btn, INPUT); // set the button's pin as an input
}

void loop()
{
Serial.println(digitalRead(btn)); // read the value of the button and print it to the serial monitor
delay(100); // delay the loop for 0.1 sec
}

Explanation

Electricity will constantly try to pass through the button (the path of least resistance); however, it only works when the button is pressed. If the button is pressed, it’s able to flow through the button and receive power from the 5V pin (red wire). This will read a 1 into your program to say that it’s receiving power. Otherwise, it’s forced to pass through the resistor and to ground. This will read a 0 into your program to say that it’s NOT receiving power.

A Step Further

Now that you know how to hook up a button and take it a step further. By using a simple if-else statement to determine if the button is pressed, you can easily turn on an LED when a button is pressed.

More code

if(digitalRead(btn) == 1) digitalWrite(13, HIGH); // if button is pressed, turn LED on
else digitalWrite(13, LOW); // else turn LED off