Arduino: Ultrasonic Distance Sensor
This is my second post detailing my Arduino Robot Car project. I will focus on using an ultrasonic distance sensor to detect obstacles and coming up with a simple algorithm to keep the car from crashing into stuff. Here is a quick video displaying the progress that can be achieved by the end of this tutorial.
It may not be the most intelligent little robot car yet, but it does OK at not running into stuff. For this post, the focus was to test out various scenarious and to get a feel of how to come up with a good solution. My next post will be an optimization of the “avoidance” algorithm.
Preparation
Unfortunately, we are going to scratch a little bit of the work you did in the last post: the switch pin. I used it in the beginning of my last project to follow along with the Arduino tutorial for motor control, and decided to leave it in the first part of my project to help me debug if something went wrong. However, now I have removed that part of the circuit and shifted some of the connections to make it more compact.
Also, you are going to have to somehow fit your Arduino, breadboard, 9V battery, and AA battery back onto your car. I am using two-sided tape so I can move things around if I need to (and I had it lying around at home). Here is a picture of what I came up with:
Ultrasonic Distance Sensor
I am using an ultrasonic distance sensor with the New Ping Library. If you scroll down to the Connection Example, you will see the following image:
We are going to make 4 connections:
- power
- ground
- trigger: causes module to send out a Ping
- echo: receives the Ping
We are going to follow the example code given to us in the Simple NewPing Sketch example:
Let’s put the sensor on our robot car with the trigger connected to Digital Input 12
and the echo connected to Digitial Input 11
. This corresponds to the code given to us in the Simple NewPing Sketch. Make sure that your breadboard connects to your Arduino as in the following photos:
Here is my code:
Conclusion
This will give you the video that you saw in the beginning. When I try it, it will work for awhile, and then get stuck in a weird corner where the algorithm doesn’t really know what to do. It will just kinda spin around and get trapped. So, there are two things that we need to do:
- write a better algorithm
- reverse the motor direction in case we get stuck
These will be covered in the next post.