Raspberry Pi and HC-SR04 distance sensor interfacing with C and Python
The inexpensive and extremely popular HC-SR04 ultrasonic distance sensors are readily available everywhere.
Even better, they are easy to use with any model Raspberry Pi!
In the photo above, you can see an HC-SR04 connected to the new Raspberry Pi Zero using two resistors and some jumper wires.
I used joan’s excellent pigpio library for testing my old C code and writing simple Python code for the HC-SR04.
As you can see above, an HC-SR04 distance sensor has four pins:
- Vcc (5V)
I connected the HC-SR04 to my Raspberry Pi Zero as follows:
The Echo pin from the HC-SR04 goes through a voltage divider before being fed to GPIO#22 – which would be damaged without the two resistors.
GPIO#18 drives the HC-SR04’s Trig pin directly – as it is an output, there is no need for a voltage divider.
All I had to change were the Trigger and Echo gpio pins to match my current test setup, and the C code worked immediately!
Ok, time to get it running with Python.
First, I downloaded the latest version of joan’s example code for the HC-SR04.
After updating the pins used for Trig and Echo, it worked immediately.
This actually had me scratching my head, as when I tried to get it working with Pi Droid Alpha a few months ago I had intermittent results.
Mind you, at that time, I was using an older version of joan’s example program, a different HC-SR04, and I had modified the code for single pin operation…
I decided to write different, simpler, Python code for using an HC-SR04 – with an eye towards later modifying it for single pin operation.
(Click Here to download the Python code I wrote for the HC-SR04 you will have to rename the file to hc-sr04.py after downloading)
To use an HC-SR04 with my hc-sr04.py library, just register two callback routines on the Echo pin, then invoke the readDistance2() functio, passing it the trigger and echo pins.
A later version of the library will add a setup function, but before I do that, I want to get single pin mode working! (I’ll update this article when that works)
Moral of the story?
Even if you had a sensor working with another microcontroller before, get the simple version of the code running before you try to get the more complex single pin mode working