# Advanced Kit 2: Distance Sensors

Planning
Step 1
In this lesson we will learn to use distance sensors which will allow our robot to detect obstacles in front of it

In this lesson we will make our robot follow our hand using two distance sensors at the front

Step 2
IR distance sensors work by sending out infrared light and collecting the reflected light

It uses IR light so that it doesn't pickup natural light in the room

The bigger the angle, the farther the object

Step 3
Attach the power pins of the sensor to your low power rail

The low power rail is supplied by the 5V output pin on your arduino

The white wire returns an analog (0 - 255) signal as opposed to a digital (HIGH/LOW) signal.

Thus it needs to be attached to an analog input pin (shown in orange).

Step 4

The only function we need for analog pins is analogRead().

We tell it which pin to read from and it returns an analog signal from 0-255

Create an integer named leftSensor and use it to store the output of the analogRead function

Step 5
Use the serial monitor to view the value of leftSensor

Remember to begin the Serial monitor with a value of 9600.

Then use println to print the value of leftSensor and thus the reading from the distance sensor to the screen

Step 6
Do the numbers get bigger or smaller as you bring your hand closer and farther from the sensor

One idea you could try if you wish would be to see if you can figure out the relationship between the sensor reading and the distance in inches or cm.

Step 7
How can we use this to check if a wall is within, say, 2 inches from the sensor?

if we read the analog pin's input, what value corresponds to an object ~2 inches away?

Use an if statement to log to the console if there is an object within around 2 inches in front of the sensor

``````if (leftSensor > ____ ) {
Serial.println("wall");
}
``````
Step 8
Attach two distance sensors to the front of your switch bot as shown below

In the next lesson we will be moving one of the distance sensors to the side of the robot, so don't make the attachments too strong.

Step 9
Set up your Serial output to make sure both of your sensors are working properly

Using `Serial.print` and `Serial.println` you can display both sensor outputs on a single line.
Remember the Serial Monitor waits until it receives a `println` command before indenting.

``````Serial.print(leftSensor);
Serial.print("   |   ");
Serial.println(rightSensor);
``````
Challenge
Step 10

The logic for this program works like this:

``````IF ( [Both sensors detect a wall] ) {
STOP
ELSE IF ( [leftSensor detects a wall] )
TURN LEFT
ELSE IF ( [rightSensor detects a wall] )
TURN RIGHT
ELSE
MOVE FORWARD
``````

Demonstration:

### Try one of these lessons next:

Advanced Kit 2: Distance Sensors Info

Account

MVCode Clubs

Created By

Course:

Autonomous Robotics: Maze Solvers

Access Level