MicroPython

MicroPython HC-SR04 Ultrasonic Sensor – ESP32 and Thonny IDE

MicroPython is widely used with microcontrollers and embedded systems. We can write code and libraries inside MicroPython IDE and interface multiple sensors. This writeup will guide you on measuring distance using the ESP32 with HC-SR04 sensor.

ESP32 with HC-SR04 Ultrasonic Sensor Using MicroPython

Interfacing ESP32 with ultrasonic just requires two wires to be connected. Using ultrasonic sensors, we can measure object distance and can trigger responses based on this system such as vehicle collision avoiding systems.

Using MicroPython which is a designed language for ESP32 and other microcontrollers we can interface multiple sensors like the HC-SR04. MicroPython code will be written which calculates the time taken by the SONAR wave to reach from sensor to object and back to object. Later using the distance formula, we can calculate object distance.

Here are some main highlights of HC-SR04 sensor:

Characteristics  Value
Operating Voltage 5V DC
Operating Current 15mA
Operating Frequency 40KHz
Min Range 2cm/ 1 inch
Max Range 400cm/ 13 feet
Accuracy 3mm
Measuring Angle <15 degree

HC-SR04 PinoutHC-SR04 contains following four pins:

  • Vcc: Connect to ESP32 Vin pin
  • Gnd: Connect to GND
  • Trig: Pin to receive control signal from ESP32 board
  • Echo: Send back signal. Microcontroller Board receives this signal to calculate distance using time

How Ultrasonic Works

After the HC-SR04 sensor is connected with ESP32 a signal at the Trig pin will be generated by board. Once the signal is received at the trig pin of HC-SR04 sensor an ultrasonic wave will be generated which leaves the sensor and hits the object or obstacle body. After hitting it will bounce back to the object surface.

A picture containing text Description automatically generated

Once the reflected wave reaches back to the sensor receiving end a signal pulse at echo pin will be generated. ESP32 receives the echo pin signal and calculates distance between object and sensor using Distance-Formula.

Text Description automatically generated

Total distance calculated should be divided by two inside the ESP32 code as the distance we get originally is equal to total distance from sensor to object and back to the sensor receiving end. So real distance is the signal which equals half of that distance.

Schematic

Following is the schematic for interfacing ESP32 with ultrasonic sensor:

A picture containing text, electronics Description automatically generated

Connect the trigger and echo pin of the sensor with GPIO 5 and GPIO 18 of ESP32 respectively. Also connect ESP32 GND and Vin pin with sensor pins.

HC-SR04 Ultrasonic Sensor ESP32 Pin
Trig GPIO 5
Echo GPIO 18
GND GND
VCC VIN

Hardware

Following components are required to program ultrasonic sensor:

  • ESP32
  • HC-SR04
  • Breadboard
  • Jumper Wires

A picture containing text Description automatically generated

How to Setup Ultrasonic HC-SR04 with ESP32 Using MicroPython

Before we can program ESP32 with an ultrasonic sensor we need to install a library in it. Connect ESP32 board to the PC. Follow along the steps to complete ESP32 configuration with ultrasonic sensor in Thonny IDE using MicroPython.

Step 1: Now open Thonny IDE. Create a new file in the editor window Go to: File>New or press Ctrl + N.

Once the new file is opened, paste the following code into the Thonny IDE editor window.

import machine, time
from machine import Pin

class HCSR04:

    # echo_timeout_us is based in chip range limit (400cm)
    def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):

        self.echo_timeout_us = echo_timeout_us
        # Init trigger pin (out)
        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
        self.trigger.value(0)

        # Init echo pin (in)
        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)

    def _send_pulse_and_wait(self):

        self.trigger.value(0) # Stabilize the sensor
        time.sleep_us(5)
        self.trigger.value(1)
        # Send a 10us pulse.
        time.sleep_us(10)
        self.trigger.value(0)
        try:
            pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
            return pulse_time
        except OSError as ex:
            if ex.args[0] == 110: # 110 = ETIMEDOUT
                raise OSError('Out of range')
            raise ex

    def distance_mm(self):

        pulse_time = self._send_pulse_and_wait()

        mm = pulse_time * 100 // 582
        return mm

    def distance_cm(self):

        pulse_time = self._send_pulse_and_wait()

        cms = (pulse_time / 2) / 29.1
        return cms

Step 2: After writing the library code inside the editor window now we have to save it inside the MicroPython device.

Text, application Description automatically generated

Step 3: Go to: File>Save or press Ctrl + S.

Graphical user interface, application, Teams Description automatically generated

Step 4: A new window will appear. Make sure that ESP32 is connected with the PC. Select MicroPython device to save library file.

Graphical user interface, application Description automatically generated

Step 5: Save the ultrasonic library file with name hcsr04.py and click OK.

Graphical user interface, application Description automatically generated

Now the ultrasonic hcsr04 sensor library is successfully added to the ESP32 board. Now we can call library functions inside code to measure distance of different objects.

Code for Ultrasonic Sensor Using MicroPython

For ultrasonic sensor code create a new file (Ctrl + N). In the editor window, enter the code given below and save it inside the main.py or boot.py file. This code will print the distance of any object that comes in front of HC-SR04.

Graphical user interface, text, application Description automatically generated

Code started by calling important libraries such as HCSR04 and time library along with sleep to give delays.

Next, we created a new object with a name sensor. This object is taking three different arguments: trigger, echo, and timeout. Here timeout is defined as the max time after the sensor goes out of range.

sensor = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=10000)

To measure and save distance a new object named distance is created. This object will save distance in cm.

distance = sensor.distance_cm()

Write the following code to get data in mm.

distance = sensor.distance_mm()

Next, we printed the result on the MicroPython IDE shell.

print('Distance:', distance, 'cm')

In the end a delay of 1 sec is given.

sleep(1)

Complete code is given below:

from hcsr04 import HCSR04
from time import sleep
# ESP32
sensor = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=10000)
# ESP8266
#sensor = HCSR04(trigger_pin=12, echo_pin=14, echo_timeout_us=10000)
while True:
    distance = sensor.distance_cm()
    print('Distance:', distance, 'cm')
    sleep(1)

After writing and saving code inside the MicroPython device, I now run the ultrasonic sensor main.py file code. Click the play button or press F5.

Graphical user interface, text, application, chat or text message Description automatically generated

Output of Ultrasonic Sensor When Object is Near

Now place an object near the ultrasonic sensor and check the measured distance on the serial monitor window of Arduino IDE.

A picture containing text Description automatically generated

Object distance is shown in the shell terminal. Now the object is placed at 5 cm from the ultrasonic sensor.

Output of Ultrasonic Sensor When Object is Far

Now to verify our result we will place objects far from the sensor and check the working of the ultrasonic sensor. Place objects like shown in image below:

A picture containing text Description automatically generated

Output window will give us a new distance and as we can see that object is far from the sensor, so the measured distance is approx. 15 cm from the ultrasonic sensor.

Graphical user interface, application, Word Description automatically generated

Conclusion

Measuring distance has a great application when it comes to robotics and other projects, there are different ways to measure distance. HC-SR04 with ESP32 can measure the distance of different objects. Here this writeup will cover all the steps one needs to integrate and start measuring distance with ESP32.

 

About the author

Kashif

I am an Electrical Engineer. I love to write about electronics. I am passionate about writing and sharing new ideas related to emerging technologies in the field of electronics.