Welcome back to Maker Tech Lab! In this tutorial, we’ll build on our previous LED blinking project and add a push button to control the LED. This project introduces the concept of digital input and is a great next step for beginners.
Materials Needed
- Arduino Uno
- LED
- 220-ohm resistor
- Push button
- 10k-ohm resistor
- Breadboard
- Jumper wires
Circuit Diagram
Let’s set up the circuit. Follow the diagram below:
- Connect the LED: Place the LED on the breadboard. Connect the longer leg (anode) to a digital pin (e.g., pin 13) on the Arduino through a 220-ohm resistor.
- Connect the Resistor: Connect the other leg of the resistor to the Arduino ground (GND).
- Connect the Push Button: Place the push button on the breadboard. Connect one leg to a digital pin (e.g., pin 2) on the Arduino.
- Add the Pull-down Resistor: Connect a 10k-ohm resistor between the push button leg connected to pin 2 and the ground rail on the breadboard.
- Complete the Circuit: Connect the other leg of the push button to the 5V pin on the Arduino.
The Code
Let’s move on to the code. We’ll use the Arduino IDE to write a program that makes the LED blink when the push button is pressed.
// Pin numbers
const int ledPin = 13;
const int buttonPin = 2;
// Variable to store the button state
int buttonState = 0;
// Setup function runs once when you press reset or power the board
void setup() {
// Initialize the LED pin as an output
pinMode(ledPin, OUTPUT);
// Initialize the push button pin as an input
pinMode(buttonPin, INPUT);
}
// Loop function runs over and over again forever
void loop() {
// Read the state of the push button
buttonState = digitalRead(buttonPin);
// Check if the button is pressed
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(1000); // Wait for a second
digitalWrite(ledPin, LOW); // Turn the LED off
delay(1000); // Wait for a second
} else {
digitalWrite(ledPin, LOW); // Ensure the LED is off
}
}
Explanation
- Pin Setup: We define the pins where the LED and the push button are connected.
- Setup Function: We initialize the LED pin as an output and the push button pin as an input.
- Loop Function: This function runs repeatedly. It reads the state of the push button. If the button is pressed, the LED blinks; otherwise, the LED remains off.
Uploading the Code
- Open the Arduino IDE.
- Copy and paste the code into the IDE.
- Select the correct board and port from the Tools menu.
- Click the upload button.
Conclusion
That’s it! You’ve successfully created a project where a push button controls an LED. This project teaches you how to use digital inputs and can be expanded to control multiple LEDs or other components. Stay tuned for more tutorials and exciting projects at Maker Tech Lab!