According to the specification of the PING))) sensor, you have to wait at least
200 microseconds between two measurements. For high-speed measurements,
we could calculate the length of a pause more accurately by actually measuring
the time the code takes. But in our case this is pointless, because all the
statements that are executed during two measurements in the
loop
method
take far more than 200 microseconds. And outputting data to the serial con-
nection is fairly expensive. Despite this, we have added a small delay of 100
microseconds to slow down the output.
You might wonder why we use the
const
keyword so often. To program the
Arduino you use C/C++, and in these languages it’s considered a good practice
to declare constant values as
const
(see Effective C++: 50 Specific Ways to
Improve Your Programs and Designs [Mey97]). Not only will using
const
make
your program more concise and prevent logical errors early, but it will also
help the compiler to decrease your program’s size.
Although most Arduino programs are comparatively small, software develop-
ment for the Arduino is still software development, and it should be done
according to all the best practices we know. So, whenever you define a con-
stant value in your program, declare it as such (using
const
, not using
#define
).
This is true for other programming languages as well, so we will use
final
in
our Java programs, too.
Now it’s time to play around with the sensor and get familiar with its strengths
and weaknesses. Compile the program, upload it to your Arduino board, and
open the serial monitor (don’t forget to set the baud rate to 9600). You should
see something like this:
Distance to nearest object: 42 cm
Distance to nearest object: 33 cm
Distance to nearest object: 27 cm
Distance to nearest object: 27 cm
Distance to nearest object: 29 cm
Distance to nearest object: 36 cm
In addition to the output in the terminal, you will see that the LED on the
PING))) sensor is turned on whenever the sensor starts a new measurement.
Test the sensor’s capabilities by trying to detect big things or very small things.
Try to detect objects from different angles, and try to detect objects that are
below or above the sensor. You should also do some experiments with objects
that don’t have a flat surface. Try to detect stuffed animals, and you will see
that they are not detected as well as solid objects. (That’s probably why bats
don’t hunt bears—they can’t see them.)
report erratum • discuss
Measuring Distances with an Ultrasonic Sensor • 83
www.it-ebooks.info