# DUE BrainBot Collision

The BrainBot is equipped with a distance sensor. You can use the distance sensor to determine how far away something is and then program the robot to avoid it.

## Prerequiste

This lesson assumes you’ve already assembled the BrainBot and know hot to do the BrainBot Dance!

## Distance Sensor

The distance sensor on the BrainBot looks like the two eyes at the front. These ‘eyes’ are what are used to transmit and receive the echo that bounces off object that it comes near. One of the ‘eyes’ is the Transmitter and the other is the Receiver.

If you’d like to know more about how distance sensors work, check out the Distance lesson.

``````@Loop
Dist()
Println(d)
Wait(200)
goto Loop ``````

When you run the program, try putting your hand close to the sensors and then pull your hand further away. You’ll notice the value changing as you move your hand. This is now reading the distance.

## Avoiding Obstacles

First, create a function to handle what the BrainBot does when it’s less than 25 centimeters from an object. Call the function you create TurnAround().

``````@Avoid
L=-40:R=-40
Move()
Wait(200)
L=40
Move()
Wait(200)
Stop()
Return ``````

Since we’re going to move the BrainBot, add a button to start the process so the BrainBot doesn’t run away when we’re testing it.

You can use the distance to make the BrainBot Avoid() the obstacle by backing up and turn around when it gets under 25 centimeters away from an object.

``````@Loop
L=40:R=40
Move()
Dist()
Println(d)
If d < 25
Avoid()
End
Wait(100)
Goto loop

@Avoid
L=-40:R=-40
Move()
Wait(200)
L=40
Move()
Wait(200)
Stop()
Wait(1000)
Return``````

## Wait for me!

In many cases, the robot will run off as soon as it is turned on. It will be a good idea to hold the program till a button is pressed. Add this to the top of your code:

``````# Wait for Button A press
Print("A to Start")
@BtnWt
Beep()
Wait(200)
Goto BtnWt
End
``````

## What’s Next?

Now that you’ve mastered moving the BrainBot around and avoiding obstacles, you can program the BrainBot to follow a specific path in the AI’s BrainBot Autonomous Lesson.

## BrainStorm

A distance sensor is what a car would use as a backup sensor. It measures the distance to what is behind and make a sound reflecting that distance. There are no intelligence there, no decision making. Some cars may have control over the breaks system and it will automatically stop the car if it detects an object that is getting too close to the car. In this case we are starting to add some intelligence and decision making.