4.0 Conditionals – if

Conditionals allow our programs to make decisions. Conditionals are evaluated on the basis of:

<Less Than
>Greater Than
==Equal to
!=Not Equal to

You are probably familiar with the less than and greater than symbols. All of these operators evaluate the value on their left against the value on their right and return true or false.

The double equals sign sometimes throws programmers off. == is an evaluation operation. It tests the value on the left against the value on the right. If they are equal it returns true, otherwise it returns false.

!= means not equal to. As with the other operator it evaluates to true or false based on whether the value on the left is not equal to the value on the right.

In an Arduino sketch we can use the if statement to make a decision.

Simple evaluation using the if statement

Notice the braces { }. They enclose the code that will be executed if the conditional evaluates to true.

What if we need to execute a different set of instructions if the condition evaluates to false? The if statement has a partner named else.

a simple if / else conditional

Create a Night Light

In section 3.0 we created a project to demonstrate the use of a photoresistor. Suppose we want to use a photoresistor to turn an LED on or off based on the level of light. We can use a conditional to turn the LED on when the readings indicate that the light level has dropped.

What observations have you made about the reading on A0 when the brightness changes at the photoresister? Can you create a conditional that turns an LED on or off based on the light level?

Create a circuit and sketch using the Arduino that causes an LED to come on when there is low light.