Difference between revisions of "Ultrasonic Sensor HC-SR04"
Jump to navigation
Jump to search
Line 43: | Line 43: | ||
= Related Tutorial Videos = | = Related Tutorial Videos = | ||
<youtube>PJdDUZWeIDs</youtube> | <youtube>PJdDUZWeIDs</youtube> | ||
+ | |||
+ | |||
+ | = Background = | ||
+ | connecting it to the ESP8266 and reading the signal in without a library/module. | ||
+ | |||
+ | Connect Trig to Pin5 and Echo to Pin4 of the ESP8266. | ||
+ | |||
+ | [[File:Hc-03.JPG]] | ||
+ | |||
+ | [[File:Hc04-03.JPG]] | ||
+ | |||
+ | [[File:Hc-sr04-1.JPG|x300px]] | ||
+ | [[File:Ultra1.JPG|x300px]] | ||
+ | |||
+ | <syntaxhighlight lang="python" line='line'> | ||
+ | import machine | ||
+ | import utime | ||
+ | |||
+ | |||
+ | while True: | ||
+ | trig=machine.Pin(5, machine.Pin.OUT) | ||
+ | trig.off() | ||
+ | utime.sleep_us(2) | ||
+ | trig.on() | ||
+ | utime.sleep_us(10) | ||
+ | trig.off() | ||
+ | echo=machine.Pin(4, machine.Pin.IN) | ||
+ | while echo.value() == 0: | ||
+ | pass | ||
+ | t1 = utime.ticks_us() | ||
+ | while echo.value() == 1: | ||
+ | pass | ||
+ | t2 = utime.ticks_us() | ||
+ | cm = (t2 - t1) / 58.0 | ||
+ | print(cm) | ||
+ | utime.sleep(2) | ||
+ | |||
+ | |||
+ | </syntaxhighlight> |
Revision as of 22:34, 30 August 2020
Contents
Description
The HC-SR04 is an ultrasonic distance sensor that can measure distances from 2cm to 400cm. It sends out an ultrasound signal and detects the echo. By measuring the time you can calculate the distance.
more details:
- https://randomnerdtutorials.com/complete-guide-for-ultrasonic-sensor-hc-sr04/
- https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
How to connect it electrically
Required Module and Files
- We use hcsr04.py
- this is downloaded from https://github.com/rsc1975/micropython-hcsr04
- the original file is at https://github.com/rsc1975/micropython-hcsr04/blob/master/hcsr04.py
How to control it in MicroPython
1 from hcsr04 import HCSR04
2 from time import sleep
3
4 sensor = HCSR04(trigger_pin=12, echo_pin=14)
5 sleep(1)
6 i=0
7
8 while True:
9 distance = sensor.distance_cm()
10 print(i, ': Distance:', distance, 'cm')
11 i=i+1
12 sleep(0.5)
Related Tutorial Videos
Background
connecting it to the ESP8266 and reading the signal in without a library/module.
Connect Trig to Pin5 and Echo to Pin4 of the ESP8266.
1 import machine
2 import utime
3
4
5 while True:
6 trig=machine.Pin(5, machine.Pin.OUT)
7 trig.off()
8 utime.sleep_us(2)
9 trig.on()
10 utime.sleep_us(10)
11 trig.off()
12 echo=machine.Pin(4, machine.Pin.IN)
13 while echo.value() == 0:
14 pass
15 t1 = utime.ticks_us()
16 while echo.value() == 1:
17 pass
18 t2 = utime.ticks_us()
19 cm = (t2 - t1) / 58.0
20 print(cm)
21 utime.sleep(2)