Programming Examples
Arduino program to turns on LED when the button is pressed once and remains on until the button is pressed again to turn it off
Arduino program to turns on LED when the button is pressed once and remains on until the button is pressed again to turn it off.
Solution
int buttonState = 0; // Variable to store the current button state
int lastButtonState = 0; // Variable to store the previous button state
int ledState = LOW; // Variable to store the LED state (initially off)
void setup()
{
// Initialize the LED pin as an output
pinMode(13, OUTPUT);
// Initialize the push button pin as an input
pinMode(2, INPUT);
}
void loop() {
// Read the current state of the push button
buttonState = digitalRead(2);
// Check if the button state has changed from the last loop
if (buttonState != lastButtonState)
{
// If the button state is HIGH (pressed)
if (buttonState == HIGH)
{
// Toggle the LED state
ledState = !ledState;
// Update the LED pin with the new state
digitalWrite(13, ledState);
}
// Delay for debouncing
delay(50);
}
// Save the current button state as the last state for the next loop
lastButtonState = buttonState;
}
Output/ Explanation: