012 - ESP32 MicroPython: HC-SR04 Ultrasonic Sensor in MicroPython
Introduction
In this video, we will learn how to use the HC-SR04 ultrasonic sensor in MicroPython. With ultrasonic sensor, it can be use for measuring distance or it can be use for sensing an object.
Circuit Diagram
Hardware Instruction
- Connect the HC-SR04 VCC pin to ESP32 VIN pin. The HC-SR04 needs 5V, trust me I already tried using the 3V3 pin, it doesn’t work.
- Connect the HC-SR04 Trigger pin to ESP32 GPIO D13.
- Connect the HC-SR04 Echo pin to ESP32 GPIO D12.
- Connect the HC-SR04 GND pin to ESP32 GND pin.
- Connect one of the buzzer pin to ESP32 GPIO D32.
- Connect the other pin of the buzzer to ESP32 GND pin.
- Download the hcsr04.py module from: Download the hcsr04.py
- Copy and paste it to Thonny Python IDE.
- Make sure that the ESP32 is plugged into the computer, then click File menu then select Save as
- Save it as main.py
Video Demonstration
Call To Action
If you have any question regarding this tutorial, please do not hesitate to write your inquiry in the comment box provided.
If you enjoy this video, please consider supporting my journey by Subscribing to my Youtube channel. Click this to Subscribe to TechToTinker Youtube channel.
Source Code
Download the hcsr04.py module from here or copy it below:
https://github.com/rsc1975/micropython-hcsr04/blob/master/hcsr04.py
Example 1, Intruder Alarm (sort of) using HC-SR04:
1import machine
2import hcsr04
3import time
4
5ultrasonic = hcsr04.HCSR04(trigger_pin=13, echo_pin=12, echo_timeout_us=1000000)
6led = machine.Pin(2, machine.Pin.OUT)
7buzzer = machine.PWM(machine.Pin(32, machine.Pin.OUT))
8buzzer.freq(4186)
9buzzer.duty(0)
10
11while True:
12 distance = ultrasonic.distance_cm()
13 print('Distance:', distance, 'cm', '|', distance/2.54, 'inch')
14 if distance <= 10:
15 buzzer.duty(512)
16 led.on()
17 else:
18 buzzer.duty(0)
19 led.off()
20 time.sleep_ms(1000)
py
Copy of hcsr04.py
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
py
Posts in this series
- 026 - ESP32 MicroPython: MFRC522 RFID Module
- 025 - ESP32 MicroPython: ESP32 Bluetooth Low Energy
- 024 - ESP32 MicroPython: How to Use SD Card in MicroPython
- 023 - ESP32 MicroPython: Binary Clock
- 022 - ESP32 MicroPython: MQTT Part 2: Subscribe
- 021 - ESP32 MicroPython: MQTT Part 1: Publish
- 020 - ESP32 MicroPython: RESTful APIs | Demo READ and WRITE
- 019 - ESP32 MicroPython: OpenWeather | RESTful APIs
- 018 - ESP32 MicroPython: Thingspeak | RESTful APIs
- 017 - ESP32 MicroPython: DHT Values Auto Updates using AJAX
- 016 - ESP32 MicroPython: Web Server | ESP32 Access Point
- 015 - ESP32 MicroPython: Web Server | ESP32 Station Mode in MicroPython
- 014 - ESP32 MicroPython: SIM800L GSM Module in MicroPython
- 013 - ESP32 MicroPython: UART Serial in MicroPython
- 011 - ESP32 MicroPython: DHT11, DHT22 in MicroPython
- 010 - ESP32 MicroPython: 0.96 OLED in MicroPython
- 009 - ESP32 MicroPython: Non-blocking Delays and Multithreading | Multitasking
- 008 - ESP32 MicroPython: Hardware Timer Interrupts
- 007 - ESP32 MicroPython: How to make some sound with MicroPython
- 006 - ESP32 MicroPython: How to control servo motor with MicroPython
- 005 - ESP32 MicroPython: Pulse Width Modulation
- 004 - ESP32 MicroPython: External Interrupts
- 003 - ESP32 MicroPython: General Purpose Input Output | GPIO Pins
- 001 - ESP32 MicroPython: What is MicroPython
- 000 - ESP32 MicroPython: How to Get Started with MicroPython
No comments yet!