Ultrasonic Sensor HC-SR04: Difference between revisions

From Sketching with Hardware at LMU Wiki
Jump to navigation Jump to search
No edit summary
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

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:

How to connect it electrically

Required Module and Files


How to control it in MicroPython

from hcsr04 import HCSR04
from time import sleep

sensor = HCSR04(trigger_pin=12, echo_pin=14)
sleep(1)
i=0

while True:
  distance = sensor.distance_cm()
  print(i, ': Distance:', distance, 'cm')
  i=i+1
  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.

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)