Just found an ultrasonic distance sensor node one of my IoT students built a few years ago.
As an exercise I've flashed the Wemos D1 Mini (the microcontroller the student used) with Micro-Python and uploaded this script. I've made use of a 'Class' to make the code easier to understand.
from machine import Pin, Timer
import time
class SRF05:
def __init__(self, trigger_pin, echo_pin):
self.trigger = Pin(trigger_pin, Pin.OUT)
self.echo = Pin(echo_pin, Pin.IN)
self.trigger.value(0)
self.timer = Timer(0)
def _send_pulse(self):
self.trigger.value(1)
time.sleep_us(10) # Send a 10us pulse
self.trigger.value(0)
def measure(self):
self._send_pulse()
while self.echo.value() == 0:
signaloff = time.ticks_us()
while self.echo.value() == 1:
signalon = time.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0343) / 2
return distance
# Initialise sensor
sensor = SRF05(trigger_pin=13, echo_pin=12)
# Main loop
while True:
distance = sensor.measure()
print("Distance:", distance, "cm")
time.sleep(1) # Delay between measurements
The _send_pulse()
method in the SRF05
class sets the trigger pin high for 10 microseconds, which initiates the measurement by sending a burst of ultrasonic pulses.
After sending the pulse, the code measures how long it takes for the echo to return. This duration is converted into a distance using the formula for the speed of sound (approx. 0.0343 cm/ÎĽs), and then it is divided by 2 to account for the echo's travel to the object and back.
As you can see it produces distance readings...
Detection distance is 2-450 cm
https://www.velleman.eu/products/view/?id=435526&country=be&lang=en