0

This code is used to toggle an arduino on and off , the problem is that i can't comprehend it at all. can someone explain to me how does it work ?

New = digitalRead(button);
  if ( New!=old)
  {
    if ( New == HIGH ){
      if (LEDstatus == LOW)
    {  digitalWrite(LED,HIGH);
    LEDstatus = HIGH;
    }
    else 
    {
      digitalWrite(LED,LOW);
      LEDstatus=LOW;
    }
    }
    old=New;
  }
  • 1
    It doesn't toggle an Arduino on and off. It toggles an Arduino's output pin on and off on button presses. – Duncan C Apr 14 at 18:38
1

First, fix the indentation:

New = digitalRead(button);
if ( New!=old) {                        // If the button state has changed
    if ( New == HIGH ) {                // If the button is now in the pressed state
        if (LEDstatus == LOW) {         // If the LED was off 
            digitalWrite(LED,HIGH);     // Turn the LED on
            LEDstatus = HIGH;           // Remember the LED state for next time
        } else {                        // The LED was on, so turn it off
            digitalWrite(LED,LOW);
            LEDstatus=LOW;              // Remember the LED state for next time
        }
    }
    old=New;
}

That makes the code a whole lot easier to understand.

It only does something when the button is pressed (switches to HIGH state). It doesn't do anything when you release the button.

Each button press changes the state of the LED.

if it was off, it turns it on. If it was on, it turns it off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.