ZachLabs Arduino

Deep Dive: if/else Statements

The following examples assume that you have two switches hooked up to pins 2 and 3 of the Arduino and configured for INPUT_PULLUP. None of what follows is specific to switches or digitalRead(); you could just as easily have used potentiometers and analogRead() like in the example above.

// Example #1 - The classic "if/else":
void loop() 
{
    if (digitalRead(2) == LOW)
    {
        // The switch on pin 2 is on.
    }
    else
    {
        // The switch on pin 2 is off.
    }
}

// Example #2 - A lone "if" statement:
void loop()
{
    if (digitalRead(3) == LOW)
    {
        // The switch on pin 3 is on.
    }
}

// Example #3 - Adding an "else if" into the mix:
void loop() 
{
    if (digitalRead(2) == LOW)
    {
        // The switch on pin 2 is on.
    }
    else if (digitalRead(3) == LOW)
    {
        // The switch on pin 2 is not on, but the switch on pin 3 is.
    }
    else
    {
        // The switches are both off.
    }
}

Note that you can have any number of else if statements after an if. The else on the end is optional, but if you use it, it must be at the end.

Logical Operators

Similar to Scratch and Python, C allows you to test multiple conditions in a single if statement by combining them with logical operators:

void loop()
{
    if (digitalRead(2) == LOW && digitalRead(3) == LOW)
    {
        // Both switches are on.
    }

    if (digitalRead(2) == LOW || digitalRead(3) == LOW)
    {
        // At least one (or both) of the switches are on.
    }
}

The and operator (&&) combines two tests together and requires both of them to be true. This is equivalent to the and keyword in Python.

The or operator (||) combines two tests together and requires at least one of them to be true. This is equivalent to the or keyword in Python.

If you intend to use && or ||, make sure you do not accidentally forget a character and use & or | by themselves. C is confusing and considers both of those to be valid, although they will do something completely different than what && and || do.