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.
- A button
- 3 jumper wires (red, black, yellow)
- Low-value resistor (330 ohm)
- USB Cable
- 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.
- Now choose 1 side (2 leads) of the button to work with. Pick 1 lead to be positive and the other to be negative.
- Place a (red) wire from a 5V pin on your Arduino to the positive lead of your button.
- Place a (yellow) wire from a digital pin on your Arduino to the ground lead of your button. Leave room for a resistor.
- 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.
- Place a (black) wire from the open end of the resistor to a ground pin on your Arduino.
- Connect the Arduino to your computer with the USB cable (A to B).
- 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.
int btn = 4; // a variable for the button's digital pin
Serial.begin(9600); // start reading values from the serial port
pinMode(btn, INPUT); // set the button's pin as an input
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
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 an LED, let’s get them working together. 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.
if(digitalRead(btn) == 1) digitalWrite(led, HIGH); // if button is pressed, turn LED on
else digitalWrite(led, LOW); // else turn LED off
2 Responses to 'How to Hook Up > Buttons'
Leave a Reply
You must be logged in to post a comment.