In this lesson, we’ll take our Blinky Light to the next level by adding a button to control the LED. Now, you’ll be able to turn the light on and off with a simple press!
Objective: Learn how to use a button to control an LED.
Materials:
- Arduino Uno board
- Breadboard
- LED (any color)
- 220-ohm resistor
- Push button
- Jumper wires
- Computer with Arduino IDE software installed
Step 1: Connecting the Button
- Find the two legs of the push button: One is normally open (NO) and the other is normally closed (NC).
- Connect the NO leg of the button to a digital input pin on the Arduino: We’ll use pin 2 in this lesson.
- Connect the other leg of the button to a ground rail on the breadboard: This completes the button’s circuit.
Step 2: Connecting the LED and Resistor (Review)
- Connect the LED and resistor as you did in Lesson 1: Make sure the LED’s longer leg is connected to a power rail and the resistor’s other leg is connected to the same row as the LED’s shorter leg.
Step 3: Connecting the Arduino (Review)
- Connect the LED’s longer leg to digital pin 13 on the Arduino: This is the output pin for the LED.
Step 4: Programming the Arduino
- Open the Arduino IDE.
- Copy and paste the following code:
const int buttonPin = 2; // Button connected to pin 2
const int ledPin = 13; // LED connected to pin 13
void setup() {
pinMode(buttonPin, INPUT); // Set button pin as input
pinMode(ledPin, OUTPUT); // Set LED pin as output
}
void loop() {
if (digitalRead(buttonPin) == HIGH) { // Check if button is pressed
digitalWrite(ledPin, HIGH); // Turn LED on
} else {
digitalWrite(ledPin, LOW); // Turn LED off
}
}
- Upload the code to the Arduino board.
Step 5: Testing the Circuit
- Press the button: You should see the LED turn on.
- Release the button: The LED should turn off.
Congratulations! You’ve created a button-controlled LED circuit!
Let’s Experiment:
- Add a delay: Try adding a delay in the loop() function to make the LED stay on for a short time after the button is pressed.
- Change the LED color: Try using a different colored LED.
Keep exploring and have fun with Arduino!