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
- GND – for the ground pin.
- VCC – for the supply voltage.
- TRIG – for the trigger signal pin.
- ECHO – for the echo signal pin.
Bill Of Materials
- ESP32 development board.
- Gorillacell ESP32 shield.
- 4-pin female-female dupont jumper wires.
- HC-SR04 ultrasonic sensor module.
Hardware Instruction
- First, attach the ESP32 board on top of the ESP32 shield and make sure that both USB port are on the same side.
- 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.
- 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.
- 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.
- Lastly, connect the ESP32 to the computer through a micro-USB cable.
Software Instruction
- Copy the example source code to Thonny IDE.
- Play with it and adapt according to your needs.
- 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
-
Purchase Gorillacell ESP32 development kit at: https://gorillacell.kr
-
HC-SR04 driver library: https://github.com/rsc1975/micropython-hcsr04/blob/master/hcsr04.py
Posts in this series
- 049 - MicroPython TechNotes: MP3 Player
- 048 - MicroPython TechNotes: Analog Touch Sensor
- 047 - MicroPython TechNotes: E108 GPS
- 046 - MicroPython TechNotes: RF433 Transceivers
- 045 - MicroPython TechNotes: Infrared Transmitter
- 044 - MicroPython TechNotes: Infrared Receiver
- 043 - MicroPython TechNotes: ESP12E WiFi | External WiFi module
- 042 - MicroPython TechNotes: JDY-32 | Bluetooth Low Energy BLE
- 041 - MicroPython TechNotes: Bluetooth HC-06
- 040 - MicroPython TechNotes: Relay
- 039 - MicroPython TechNotes: Electromagnet
- 038 - MicroPython TechNotes: Buzzer
- 037 - MicroPython TechNotes: Servo Motor
- 036 - MicroPython TechNotes: Stepper Motor
- 035 - MicroPython TechNotes: Dual Motor Driver
- 034 - MicroPython TechNotes: DC Motors | Gear Motor and Fan Motor
- 033 - MicroPython TechNotes: TCS34725 RGB Color Sensor
- 032 - MicroPython TechNotes: BMP280 Sensor
- 031 - MicroPython TechNotes: TOF Distance Sensor
- 030 - MicroPython TechNotes: DS3231 RTC
- 028 - MicroPython TechNotes: DHT11 Temperature and Humidity Sensor
- 027 - MicroPython TechNotes: Rotary Encoder
- 026 - MicroPython TechNotes: Light Dependent Resistor (LDR)
- 025 - MicroPython TechNotes: Joystick
- 024 - MicroPython TechNotes: Slider Switch
- 023 - MicroPython TechNotes: Continuous Rotation Potentiometer
- 022 - MicroPython TechNotes: Potentiometer | Reading an Analog Input
- 021 - MicroPython TechNotes: Color Touch Sensor
- 020 - MicroPython TechNotes: Touch Sensor
- 019 - MicroPython TechNotes: Switch Module
- 018 - MicroPython TechNotes: Button | Reading an Input
- 017 - MicroPython TechNotes: LASER Module
- 016 - MicroPython TechNotes: RGB LED Matrix
- 015 - MicroPython TechNotes: Neopixel 16
- 014 - MicroPython TechNotes: 8x8 Dot Matrix Display (I2C)
- 013 - MicroPython TechNotes: 8x16 Dot Matrix Display (SPI)
- 012 - MicroPython TechNotes: 8x8 Dot Matrix Display (SPI)
- 011 - MicroPython TechNotes: 1.3 OLED Display
- 010 - MicroPython TechNotes: 0.96 OLED Display
- 009 - MicroPython TechNotes: 7 Segment Display
- 008 - MicroPython TechNotes: 16x2 LCD
- 007 - MicroPython TechNotes: RGB LED
- 006 - MicroPython TechNotes: Traffic Light LED Module
- 005 - MicroPython TechNotes: Gorilla Cell LED | MicroPython Hello World
- 004 - MicroPython TechNotes: Gorilla Cell I/O Devices
- 003 - MicroPython TechNotes: Gorillacell ESP32 Shield
- 002 - MicroPython TechNotes: Introduction for Gorillacell ESP32 Dev Kit
- 001 - MicroPython TechNotes: Get Started with MicroPython
- 000 - MicroPython TechNotes: Unboxing Gorillacell ESP32 Development Kit
No comments yet!