Difficulty Level: Beginner
This tutorial demonstrates how to toggle an LED on and off using a push button. The button will act as a switch, and every press will toggle the LED's state (on or off).
Follow the wiring diagram below to connect the button and LED:
The code below will toggle the LED's state every time the button is pressed. It uses the digitalRead()
function to read the button’s state and the digitalWrite()
function to change the LED state.
digitalRead()
: Reads the current state of the button (either HIGH or LOW).digitalWrite()
: Turns the LED on or off based on the current state.if
condition: Detects if the button is pressed and toggles the LED accordingly.Here is the Arduino code to toggle the LED state with a button press:
// Define pins for LED and button
const int buttonPin = 2; // Pin connected to the button
const int ledPin = 13; // Pin connected to the LED
// Variables to track LED state and button press
int ledState = LOW; // Initial LED state is OFF
int buttonState = HIGH; // Initial button state
int lastButtonState = HIGH; // Tracks the last button state
void setup() {
// Set LED pin as output
pinMode(ledPin, OUTPUT);
// Set button pin as input
pinMode(buttonPin, INPUT_PULLUP); // Internal pull-up enabled
}
void loop() {
// Read the current button state
buttonState = digitalRead(buttonPin);
// Detect button press (button state goes from HIGH to LOW)
if (buttonState == LOW && lastButtonState == HIGH) {
// Toggle the LED state
ledState = !ledState;
// Write the new state to the LED pin
digitalWrite(ledPin, ledState);
// Debounce delay to prevent multiple toggles
delay(50);
}
// Store the current button state as the last state
lastButtonState = buttonState;
}
In this experiment, you learned how to use a button to toggle the state of an LED. This setup can be extended to other projects where you need to control different devices using buttons.