I found the following example of code (link) to make a momentary pushbutton act as a toggle switch. With the exception of one extra curly bracket at the very end of the sketch (which I deleted), it compiles and works correctly on my Arduino Uno.
//Let's say you have your push button on pin 2
int switchState = 0; // actual read value from pin2
int oldSwitchState = 0; // last read value from pin2
int lightsOn = 0; // is the switch on = 1 or off = 0
void setup() {
pinMode(2, INPUT); // push button
pinMode(3, OUTPUT); // anything you want to control using a switch e.g. a Led
}
void loop() {
switchState = digitalRead(2); // read the pushButton State
if (switchState != oldSwitchState) // catch change
{
oldSwitchState = switchState;
if (switchState == HIGH)
{
// toggle
lightsOn = !lightsOn;
}
}
if(lightsOn)
{
digitalWrite(3, HIGH); // set the LED on
} else {
digitalWrite(3, LOW); // set the LED off
}
}
}
My question is about the last IF/ELSE statement at the end of the code:
if(lightsOn)
{
digitalWrite(3, HIGH); // set the LED on
} else {
digitalWrite(3, LOW); // set the LED off
}
The Arduino Reference page for the IF statement and the IF/ELSE statement both say that Comparison Operators are required for the IF portion of the statement. The above code not have a Comparison Operator but it does work correctly. Why? Is the code...
if(lightsOn)
... a shortcut that means: if (lightsOn)==HIGH?
Matt