Using Sensors

While these little robots don’t have gyros or cameras, they do have a infrared sensor 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 Microcontroller 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.

In general, we should not create multiple instances of the same device and since we will be using this sensor in more than one command, we should create the instance in our RobotContainer class. Looking at it’s constructor, we see that the constructor for DigitalInput takes the number of the pin to be read. The IR sensor is connected to pin Device.IO_4, so add the following to your RobotContainer:

Now your DriveToLineCommand is going to need access to this sensor, so we will pass it in as a parameter to DriveToLineCommand’s 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 DriveToLineCommand.java 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!