from machine import Pin, ADC, time_pulse_us
import time as t
# CONSTANTS
# =========
# ultrasonic
echo = Pin(18, Pin.IN)
trig = Pin(19, Pin.OUT, value=0)
# other sensors
ldr = ADC(Pin(35, Pin.IN))
gas = ADC(Pin(25, Pin.IN))
# leds
light = Pin(15, Pin.OUT, value=0)
danger_light = Pin(2, Pin.OUT, value=0)
# thresholds
VEHICLE_DIST = 30
DANGER_DIST = 15
GAS_LIMIT = 3000
LIGHT_THRES = 1500
# FUNCTIONS
# =========
def get_distance() -> float:
"""
return the ultrasonic sensor reading in centimeters
note: return None if no data was returned by the sensor
"""
trig.value(0)
t.sleep_us(2)
trig.value(1)
t.sleep_us(10)
trig.value(0)
duration = time_pulse_us(echo, 1, 30000)
if duration < 0:
return None
return duration / 58
def handle_distance(d) -> str:
"""process the distance reading and return a string representing the current state"""
if d is None:
return "No Signal"
elif d < DANGER_DIST:
return "Danger"
elif d < VEHICLE_DIST:
return "Vehicle"
else:
return "Clear"
def handle_gas(g) -> str:
"""process the gas reading and return a string representing the current state"""
if g > GAS_LIMIT:
return "Danger"
else:
return "Clear"
def handle_light(l) -> str:
"""process the light reading and return a string representing the current state"""
if l > LIGHT_THRES: # not enough light
return "Dark"
else:
return "Light"
# MAIN LOOP
# =========
while True:
d_state = handle_distance(get_distance())
g_state = handle_gas(gas.read())
l_state = handle_light(ldr.read())
if d_state.lower() == "danger" or g_state.lower() == "danger":
danger_light.value(1)
else:
danger_light.value(0)
if l_state.lower() == "dark":
light.value(1)
else:
light.value(0)
print(f"[{t.time()}s]:")
print(f"\tDistance => {d_state}")
print(f"\tGas => {g_state}")
print(f"\tLight => {l_state}")
t.sleep(2)