As with the IR sensors, we can use the sonar sensor as input for the motors to aid in the movement of the robot. Depending on what you want to do, you can use the distance for different goals.
//Your Code Here
Now for a small departure from what we have done in the past. Instead of providing you to code to copy in, you are going to write the code yourself. There is no need to worry though, you know all that you need to do it and you have example code in this tutorial and the previous tutorials you have completed. And if you get stuck, don't hesitate to go back and look through them again. The following questions will help guide you in how you should write your program.
Can you write a code that makes the robot move forward until it is a specified distance from an object in front of it? (the distance is your choice, 6 inches for example).
Can you write a code that makes the robot move backward to a safe (specified) distance if an object is too close?
Can you write a code that will have the robot stay a specified distance from an object, moving forward if the object moves away and moving backward if the object gets too close?
Don’t worry if you get stuck, work through it line by line, thinking about what you want the robot to do. Examples code to help can be found here (link), but you are encouraged to work through it on your own first.