Now that we have added the motors and have the robot moving around, it’s time to use the Infrared sensor to make it a bit more intelligent.
Using the IR sensor, we can program the robot to stay on a table like this one:
As you can see, the table is black in the middle and has a white border. Since the IR sensor is on the bottom of the robot facing the floor, we will be able to tell whether we are currently over black or over white. Based on this information, we can make decisions on how the robot should behave.
For example to stay on the table a simple strategy could be:
This strategy is a starting point which you can build from.
In the driving motors blog post you wrote functions for going forward and reverse and turning. Now we will need to use those functions. The only difference this time is that when those functions are called is dependent on what the IR sensor value is.
You will first need to know roughly what value the IR sensor returns when the robot is on black and when it is on white.
This example is missing some parts that you will have to figure out:
// RoboSlam example: IR sensor control
// Declare an integer variable to store the IR readings
// The setup routine runs once when the power is switched on.
// Digital outputs for left motor
// Digital outputs for right motor
// The loop routine runs over and over until the power is switched off.
// Read the voltage on pin A0 (the IR sensor voltage)
ir_val = analogRead(IR_PIN);
// Choose motor action based on IR reading
if (ir_val > 100)
//Full steam ahead!!!
else if (ir_val < 100 )
//do a turn!!
The goal is program the robot so that it can drive around on the table for 60 seconds without falling off.
Try playing around with the timing so the robot will reverse for a bit longer or turn for longer etc. can you make the robot better at staying on the table?