Lesson 5: Button
Lesson 5: Button
Lesson: Button
Objective: At the end of this lesson, you will be able to control the state of an LED using a push button with an Arduino board.
Materials Required:
- Arduino board
- LED (any color)
- Push button
- 10k-ohm resistor
- Jumper wires
- USB cable
Circuit Connections:
- Connect the longer leg (anode) of the LED to digital pin 13 on the Arduino board.
- Connect the shorter leg (cathode) of the LED to a 220-ohm resistor.
- Connect the other end of the resistor to the ground (GND) pin on the Arduino board.
- Connect one terminal of the push button to digital pin 2 on the Arduino board.
- Connect the other terminal of the push button to the ground (GND) pin on the Arduino board.
- Connect a 10k-ohm resistor from digital pin 2 to the 5V pin on the Arduino board
Arduino Code:
void setup() {
pinMode(13, OUTPUT); // Set digital pin 13 as output for LED
pinMode(2, INPUT_PULLUP); // Set digital pin 2 as input with internal pull-up resistor
}
void loop() {
int buttonState = digitalRead(2); // Read the state of the push button
if (buttonState == LOW) { // Button is pressed
digitalWrite(13, HIGH); // Turn on the LED
} else { // Button is not pressed
digitalWrite(13, LOW); // Turn off the LED
}
}
Experiment Steps:
- Set up the circuit connections as described above.
- Connect the Arduino board to your computer using a USB cable.
- Open the Arduino IDE software and create a new sketch.
- Copy and paste the provided code into the Arduino IDE.
- Click the "Upload" button to upload the code to the Arduino board.
- Press and release the push button to control the state of the LED, turning it on or off.
Explanation:
The Arduino code above uses a push button to control the state of an LED. The pinMode()
function is used to set digital pin 13 as an output for the LED and digital pin 2 as an input with an internal pull-up resistor for the push button.
Inside the loop()
function, the digitalRead()
function is used to read the state of the push button. If the button is pressed and its state is detected as LOW, the digitalWrite()
function is used to turn on the LED by setting the digital pin 13 to HIGH. If the button is not pressed and its state is detected as HIGH, the digitalWrite()
function is used to turn off the LED by setting the digital pin 13 to LOW.
By pressing and releasing the push button, you can control the state of the LED, turning it on or off accordingly.
Challenge: Can you modify the code to make the LED toggle its state with each press of the button? For example, if the LED is off, pressing the button will turn it on, and pressing it again will turn it off.
Comments
Post a Comment