#importation of libraries needed
from machine import Pin
import utime
#assigning or hardwares to a GPIO pin of the micro controller
trigger = Pin(16, Pin.OUT)
echo = Pin(17, Pin.IN)
relay = Pin(15, Pin.OUT)
#a fuction that calculates the time and distance from our ultrasonic sensor
def u_sensor():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
total_time = signalon - signaloff
distance = (total_time * 0.0343)/2
max_d = 100
min_d = 10
mid_d = 70
print(f"The distance from object is {distance}cm")
if distance <= min_d:
relay.off()
elif mid_d <= distance <= max_d:
relay.on()
if min_d <= distance <= mid_d:
if relay.off():
print()
elif distance < mid_d:
relay.on()
#the loop that runs the whole code over and over
while True:
u_sensor()
utime.sleep(1)