Project #2: How to use a button with LED
Hook up 5 volts to one side of a button and to the other side of the button we connect pin 2. When you press the button it completes an electrical connection, pin 2 will “see” the 5 volts and if we digitalRead() at pin 2, it will report HIGH. During the times the button is not being pressed, pin 2 reports LOW.To turn on an LED by pressing the button, we simply make an if statement whose condition says something like “…if the voltage at pin 2 is HIGH, turn on the LED at pin 13…” It is really that easy.
We also have pin 2 connected to ground at all times through a resistor. This is because when we read values at pin 2, we want to get either a HIGH or a LOW reported. If pin 2 is not connected to ground, then when the button is not being pressed it becomes what is called a floating pin ( it’s not connected to anything). Floating pins on the Arduino are fine for the most part, unless you are trying to record an input from them, then they are bad, and can give you spurious information.
- Connect one of the Arduino GND pins to one of the long power rails on the breadboard – this will be the ground rail.
- Connect the short leg of the LED to this same ground rail on the breadboard then connect the long leg to a row on the breadboard.
- Connect the 220-ohm resistor from pin 13 to the same row that you have the long leg of the LED attached.
- Place the pushbutton on the breadboard. Most buttons will straddle the center trench on the breadboard.
- Connect a jumper wire from the 5-volt pin to one side of the pushbutton.
- Connect a jumper wire from pin 2 to the other side of the pushbutton.
- Connect one side of the 10k resistor from the ground rail on the breadboard to the other side to the pushbutton – on the same side that pin 2 connects.
- Plug the Arduino board into your computer with a USB cable.
- Open the Arduino IDE.
- Open the sketch for this section.
- Click the Verify button on the top left. It should turn orange and then back to blue.
- Click the Upload button. It will also turn orange and then blue once the sketch has finished uploading to your Arduino board.
- Press the button a couple times and see how the LED at pin 13 reacts.