Your robot can detect things other than the amount of light in an area. Another common sensor is an Infrared Object Detection Sensor or IR Sensor. These work by emitting IR light and watching for it to bounce off an object and come back. If the sensor sees IR light, then the must be something in front of it. Wiring the sensor is very similar to the light sensor except that we'll pull it into digital Pin 2 (labelled "2" on the board). See the wiring diagram on the right for additional details.
Once it's wired in, we'll use the code below to check that it's working. This code will display the text "Object?" followed by either a 1 or 0. A 1 means that it doesn't sense an object and a 0 means it does. This will be displayed in the Serial Monitor that we used for the first Light Sensor program, so check there if you don't remember how to launch the monitor.
Here's what the written code looks like that is generated from this ArduBlock code:
void setup()
{
Serial.begin(9600);
pinMode (2,INPUT);
}
void loop()
{
Serial.print( "Object?" );
Serial.print( " " );
Serial.print( digitalRead(2) );
Serial.print( " " );
Serial.println("");
delay( 250 );
}
Once you run this and get 1s and 0s when you're supposed to, you are ready to use this sensor for autonomous driving where the robot will watch of objects and avoid running into them.