IF /ELSE statements : Blinking an LED based on sensor input

An if statement is an important concept to learn for this workshop because at the end of the day, a robot is just a collection of if statements, it changes it’s outputs based on the sensors inputs.

You have already blinked an LED and connected the IR sensor to the Arduino. Let’s combine these two things using an if statement.

Let’s take a look at a graph of the IR sensor values:

You can see that the values returned vary between roughly 0-1000.

Using an if statement we could have the Arduino light the LED if the value was over or under a certain value.

Take a look at the code that we used to read the IR sensor value and print it over the serial port:

 

We can build on this example and add an if statement into the loop() function as seen below:

Example 1:

Let’s take a look at what this program does.

Lines 10 and 11 have been added in to set the LED pin as an output and make the output LOW so the LED is off when the program starts.

Lines 21-24 contain the new IF statement. The only way the LED pin will go HIGH is if the IR sensor value drops below 100.

Test this program out for yourself by uploading it to the Arduino. Before you upload it, position the sensor so that there is nothing in front of it, point it at the ceiling or something like that.

Once the program is uploaded, open the serial monitor and look the the sensor values. They should be more than 100. The LED will only turn on when that value drops below 100. Put your hand in front of the sensor until the value drops below 100.

The LED should turn on.

Remove your hand and watch the sensor values go back above 100.

What happens to the LED? Does it stay on or turn off again?

 

 

 

 

 

It stays on! Why?

Because there is nothing to turn it off again. Our if statement only says if the sensor value goes below 100, make the LED pin HIGH. If the sensor value goes above 100 there is nothing that tells the Arduino to make the pin LOW again. This is were the ELSE part of IF / ELSE statements come in.

Let’s change the above code to include an ELSE statement:

Example 2:

 

If we were to explain the IF/ELSE statement now in english it would be:

If the sensor value is less that 100, make the LED pin HIGH

ELSE (if the sensor value is > 100) make the LED pin LOW

Upload this code to your Arduino, open the serial monitor and move your hand in front of the sensor to see what happens.

 

This is just a basic introduction to IF/ELSE statements but if you can understand this page then you are well on the way to being able to program the robot:)

 

 

 

 

 

 

This entry was posted in Tutorial and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *