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;
 }
Dave X
2,35015 silver badges29 bronze badges
asked Apr 14, 2019 at 17:54
1
  • 1
    It doesn't toggle an Arduino on and off. It toggles an Arduino's output pin on and off on button presses. Commented Apr 14, 2019 at 18:38

1 Answer 1

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.

Greenonline
3,1527 gold badges36 silver badges48 bronze badges
answered Apr 14, 2019 at 18:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.