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;
}
-
1It doesn't toggle an Arduino on and off. It toggles an Arduino's output pin on and off on button presses.Duncan C– Duncan C2019年04月14日 18:38:41 +00:00Commented Apr 14, 2019 at 18:38
1 Answer 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.