Using Sensors

While these little robots don’t have gyros or cameras, they do have two light sensors that we are going to use to detect black lines. Our first command will be one that will simply drive the robot forward until it sees the black line and then stops. Let’s call this new command DriveToLineCommand. Go ahead and set up the framework for this new command.

The light sensors are connected to the Arduino via one of its digital input pins. Reading the state of that pin will tell us if the sensor is seeing the line or not. The class that reads the digital input pins is called DigitalInput so we will need a variable of this type. We see that the constructor for DigitalInput takes the number of the pin to be read. Looking at how the robot is wired, we see that the left sensor is attached to pin 10.

Note that, once again, we have defined a constant for the pin number and used that constant in the call to the constructor.

In the initialize() function we need to start our robot driving forward:

while defining k_speed as:

which will make the robot drive forward at half speed.

Next we need to return true from the isFinished() function when the sensor ‘sees’ the line. To check this we call the get() function of our DigitalInput class. If the light sensor ‘sees’ bright (i.e. no black line), then get() will return false. If the sensor ‘sees’ dark (i.e. black line is present), then get() will return true. Hence we need to declare our isFinished() as follows:

Finally, we need to turn off the motors in the end() functions:

Your file should now look like:

Finally connect this command to button 7 on the joystick:

Now deploy your program. Place the robot a couple of inches from the black line and verify that it stops when it reaches the line.

Next: Escape!