Connecting an ultrasonic sensor to ESP32

25. januar 2019

In this tutorial I will show you how to connect your ultrasonic range sensor to ESP32 displaying the data though serial monitor.I will be using the HC-SR04 ultrasonic sensor, which is a module that measures the distance from an object using sonar. It works by sending out a high pulse and calculating how long it takes before it returns.

Hardware

1 x ESP32 OLED

1 x HC-SR04 Ultrasonic Sensor

4 x Wire

Schematics

The HC-SR04 has 4 pins which includes Vcc, Gnd, Trig and Echo.

GND

Gnd

5V

Vcc

Pin 13

Echo

Pin 12

Trig

Trig and echo need to be connected to digital pins, so on this example I have connected them to 13 and 12 on the ESP32. This may vary depending on what kind of microcontroller you have.

Source Code

Start with defining each pin, echo and trig. After that you need to define the type of variables that will be used, which is long duration and long distance. In setup() the serial monitor is initialized and set the trigPin to OUTPUT and echoPIN to INPUT.

In loop() you start by sending a low pulse to clear the trigger though digitalWrite(trigPin, LOW), with a short delay of 5 microseconds after. Then you do the same, only now with a high pulse and 10 microseconds delay. This is the pulse we will be looking for later I the loop.

To get the duration of the high pulse, you need to use pulseIn(echoPin, HIGH) and store it in the duration variable.

The distance in cm can be calculated by dividing the duration by 2 and dividing the result by 29.1. If you want, you can get the result in inches by diving it by 74 instead.

Finally, the result is ready to be printed out in serial monitor using Serial.print(distance).