Ultrasonic Sensor HC-SR04

From Sketching with Hardware at LMU Wiki
Jump to navigation Jump to search

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.

Hc-sr04-1.JPG Ultra1.JPG

more details:

How to connect it electrically

Hc-sr04-e.JPG

Required Module and Files


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.

Hc-03.JPG Hc04-03.JPG Hc-sr04-1.JPG


 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)