2018-07-26 19:23:01 by Tim
ESP32 Arduino Ultrasonic Sensor Distance Measurements
Using the ESP32 with an OLED display as a base I’m going to connect an ultrasonic sensor to measure distance.
Arduino Ultrasonic Sensor for Distance
You can get the HC-SR04 ultrasonic sensor pretty much anywhere for less than $10 USD. On Amazon for example you can get a 5 pack:
The HC-SRO4 has 4 pins: Ground, VCC (5V), Echo (Any digital GPIO), and Trigger (Any digital GPIO). The specs give some information on accuracy and detection range. You can find the datasheet at Sparkfun.
There are a lot of good tutorials out there on how to setup and use this sensor but basically you send a pulse out on the Trigger pin (configured as an output) and then listen for a ping response on the Echo pin (configured as an input). Based on the time it takes for the echo to bounce or ping back you can calculate the distance. Below is an example of the setup and calculation from a tutorial by How To Mechtronics:
Wiring and Example Code for ESP32 Arduino Ultrasonic Sensor for Distance Measurement
Below is how I have the ultrasonic sensor wired up to the ESP32.
For reference here is the ESP32 pinout showing the available GPIO pins:
For the Arduino code there are lots of examples out there – I like the Sparkfun tutorial found here.
No external libraries are needed here – you setup the Trigger to send out the 10us pulse high and then you listen on the Echo pin input and calculate the distance.
Tip: I did run into some problems getting an accurate distance measurement. It wasn’t the raw echo pin measured delay time though it was converting that round-trip time into distance. There are a lot of code samples available and some of them don’t seem to calculate the right distance.
I found the best distance calculations came right from the datasheet:
Here’s the measured distance at 7 inches: (The measured distance is from the end of the silver acoustic component.)
And here’s the relevant code for the ultrasonic sensor distance measurement:
I haven’t done extensive accuracy tests but so far it seems to be within 1 to 2 cm which is a larger error range than the specified 0.3cm in the datasheet. Some people have done some work on this already and you can read about several ways to increase the accuracy and range of this ultrasonic sensor here.
Summary for ESP32 Arduino Ultrasonic Sensor Distance Measurement
Using this low-cost ultrasonic sensor it’s easy to connect it to a compatible Arduino device and use it as a distance range finder.