Reading an ultrasonic distance sensor

To be able to write code for the distance sensor, we will need to look at a few areas of its operation. As suggested previously, this system works by bouncing sound pulses off of objects, and timing their travel time.

A pulse is used on the trigger pin to ask for a sound pulse and timing to be sent. 10 microseconds is this pulse length, that is, 0.00001 seconds:

The echo pin responds by returning a pulse with a length corresponding to the sound travel time. The following diagram shows the timing of these:

Timing of a pulse and the response for an HC-SR04 distance sensor

By measuring the time between the ...

Get Learn Robotics Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.