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


ON 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


Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz