029 - MicroPython TechNotes: HC-SR04 Ultrasonic Sensor

Introduction

In this article, we will learn how to use an HC-SR04 Ultrasonic Sensor with ESP32 using MicroPython programming language.

Pinout

  1. GND – for the ground pin.
  2. VCC – for the supply voltage.
  3. TRIG – for the trigger signal pin.
  4. ECHO – for the echo signal pin.

Bill Of Materials

  1. ESP32 development board.
  2. Gorillacell ESP32 shield.
  3. 4-pin female-female dupont jumper wires.
  4. HC-SR04 ultrasonic sensor module.

Hardware Instruction

  1. First, attach the ESP32 board on top of the ESP32 shield and make sure that both USB port are on the same side.
  2. Next, attach the dupont wires to the ultrasonic sensor and follow the color coding which is black for the ground, red for the VCC, yellow for the TRIG pin, and white for the ECHO pin.
  3. Next, attach the other end of the dupont wires to the ESP32 shield by matching the colors of the wires to the colors of the pin headers that is black to black, red to red, yellow and the following colors to yellow pin headers. For this experiment, I choose GPIO 21 for the TRIG pin and GPIO 22 for the ECHO pin.
  4. Next, power the ESP32 shield with an external power supply with a type-C USB cable and make sure that the power switch is set to ON state.
  5. Lastly, connect the ESP32 to the computer through a micro-USB cable.

Software Instruction

  1. Copy the example source code to Thonny IDE.
  2. Play with it and adapt according to your needs.
  3. Enjoy and happy tinkering.

Video Demonstration

Call To Action

For any concern, write your message in the comment section.

You might also like to support my journey on Youtube by Subscribing. Click this to Subscribe to TechToTinker.

Thank you and have a good days ahead.

See you,

– George Bantique | tech.to.tinker@gmail.com

Source Code

1. Example # 1, exploring the basics of HC-SR04:

 1# More details can be found in TechToTinker.blogspot.com 
 2# George Bantique | tech.to.tinker@gmail.com
 3
 4from machine import Pin
 5from machine import Timer
 6from hcsr04 import HCSR04
 7
 8ultrasonic = HCSR04(trigger_pin=21, echo_pin=22, echo_timeout_us=1000000)
 9
10def timer0_callback(timer):
11    print('Distance: {}cm'.format(ultrasonic.distance_cm()))
12    #print('Distance: {}mm'.format(ultrasonic.distance_mm()))
13    #print('Distance: {}inch'.format(ultrasonic.distance_cm()/2.54))
14
15timer0 = Timer(0)
16timer0.init(period=500, mode=Timer.PERIODIC, callback=timer0_callback)

2. Example # 2, HC-SR04 intruder alarm application:

 1# More details can be found in TechToTinker.blogspot.com   
 2 # George Bantique | tech.to.tinker@gmail.com  
 3 from machine import Pin  
 4 from hcsr04 import HCSR04  
 5 from time import sleep_ms  
 6 ultrasonic = HCSR04(trigger_pin=21, echo_pin=22, echo_timeout_us=1000000)  
 7 led = Pin(2, Pin.OUT)  
 8 while True:  
 9   distance = ultrasonic.distance_cm()  
10   print('Distance:', distance, 'cm')  
11   if distance <= 10:  
12     print('ALERT! Intruder detected.')  
13     led.value(not led.value())  
14   else:  
15     led.value(0)  
16   sleep_ms(500)  

3. hcsr04.py driver library:

 1import machine, time
 2from machine import Pin
 3
 4__version__ = '0.2.0'
 5__author__ = 'Roberto Sánchez'
 6__license__ = "Apache License 2.0. https://www.apache.org/licenses/LICENSE-2.0"
 7
 8class HCSR04:
 9    """
10    Driver to use the untrasonic sensor HC-SR04.
11    The sensor range is between 2cm and 4m.
12    The timeouts received listening to echo pin are converted to OSError('Out of range')
13    """
14    # echo_timeout_us is based in chip range limit (400cm)
15    def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):
16        """
17        trigger_pin: Output pin to send pulses
18        echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor
19        echo_timeout_us: Timeout in microseconds to listen to echo pin. 
20        By default is based in sensor limit range (4m)
21        """
22        self.echo_timeout_us = echo_timeout_us
23        # Init trigger pin (out)
24        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
25        self.trigger.value(0)
26
27        # Init echo pin (in)
28        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)
29
30    def _send_pulse_and_wait(self):
31        """
32        Send the pulse to trigger and listen on echo pin.
33        We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
34        """
35        self.trigger.value(0) # Stabilize the sensor
36        time.sleep_us(5)
37        self.trigger.value(1)
38        # Send a 10us pulse.
39        time.sleep_us(10)
40        self.trigger.value(0)
41        try:
42            pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
43            return pulse_time
44        except OSError as ex:
45            if ex.args[0] == 110: # 110 = ETIMEDOUT
46                raise OSError('Out of range')
47            raise ex
48
49    def distance_mm(self):
50        """
51        Get the distance in milimeters without floating point operations.
52        """
53        pulse_time = self._send_pulse_and_wait()
54
55        # To calculate the distance we get the pulse_time and divide it by 2 
56        # (the pulse walk the distance twice) and by 29.1 becasue
57        # the sound speed on air (343.2 m/s), that It's equivalent to
58        # 0.34320 mm/us that is 1mm each 2.91us
59        # pulse_time // 2 // 2.91 -> pulse_time // 5.82 -> pulse_time * 100 // 582 
60        mm = pulse_time * 100 // 582
61        return mm
62
63    def distance_cm(self):
64        """
65        Get the distance in centimeters with floating point operations.
66        It returns a float
67        """
68        pulse_time = self._send_pulse_and_wait()
69
70        # To calculate the distance we get the pulse_time and divide it by 2 
71        # (the pulse walk the distance twice) and by 29.1 becasue
72        # the sound speed on air (343.2 m/s), that It's equivalent to
73        # 0.034320 cm/us that is 1cm each 29.1us
74        cms = (pulse_time / 2) / 29.1
75        return cms

References And Credits

  1. Purchase Gorillacell ESP32 development kit at: https://gorillacell.kr

  2. HC-SR04 driver library: https://github.com/rsc1975/micropython-hcsr04/blob/master/hcsr04.py



Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.