Decision making

Programming theory

In programming, an if statement is a construct that causes the program to act differently depending upon some condition. We already saw this in Lesson 3:

if (counter == 15) {
  Serial.println("Resetting ...");
  counter = 0;

Here, the code inside curly braces is only run if counter is equal to 15.

Common comparisons are:

Operator Meaning Example
== Equal to if (x == 7) { }
< Less than if (x < 7) { }
<= Less than or equal to if (x <= 7) { }
> Greater than if (x > 7) { }
>= Greater than or equal to if (x >= 7) { }


Use the same circuit as the previous lesson.


Develop a “night light” that will turn on the LED when the light sensor reads a low value. You can simulate “night” by covering the sensor with your finger to block the light. You will need to use your previous program to determine typical values that correspond to “dark” vs “light”.

Hint: You might find it helpful to look at pages 19 – 20 of the Arduino Notebook.

Don’t forget to save your code into a new file so that you don’t overwrite your previous work.

Extension task

Use two different LEDs (e.g. the one built into the Arduino on pin 13, and the one on your breadboard) to signal different levels of darkness. For example, if it is very dark, you might light up both, whereas if it is only moderately dark, you might light up a just a single LED. Use an if-else if-else construct to express this idea (see the Arduino Notebook page 20).

This work is licensed under a Creative Commons Attribution 4.0 International License. For comments or corrections, please contact [email protected].