from machine import Pin, ADC, time_pulse_us
from time import sleep, sleep_us
import network
import BlinkLib
system_status = "ENERGY SAVE"
# Sensors Initilization
trig = Pin(12, Pin.OUT)
echo = Pin(14, Pin.OUT)
gas = ADC(Pin(34))
gas.atten(ADC.ATTN_11DB) # Full Range 0 - 3.3V to 0 - 4059
# LEDs
tunnel_light = Pin(4, Pin.OUT)
red_light = Pin(15, Pin.OUT)
# Threshold
VEHICLE_DIST = 30 #cm
DANGER_DIST = 15 #cm
GAS_LIMIT = 2000
LIGHT_THRESHOLD = 1500
# Distance
def get_distance():
trig.value(0)
sleep_us(2)
trig.value(1)
sleep_us(10)
trig.value(0)
duration = time_pulse_us(echo, 1, 30000) # 30000 if micro second if echo stays high that we ignore it
if duration < 0 :
return None
return(duration * 0.343) / 2
# STATE FUNC
def distance_state(d):
if d is None:
return "NO SIGNAL"
elif d < DANGER_DIST:
return "TOO CLOSE"
elif d < VEHICLE_DIST:
return"VEHICLE"
else:
return "CLEAR"
def gas_state(g):
if g > GAS_LIMIT:
return "DANGER"
else:
return "SAFE"
while True:
distance = get_distance()
gas_value = gas.read()
dist_status = distance_state(distance)
gas_status = gas_state(gas_value)
# GAS DANGER (HIGHEST PRIORITY) - (RED LED)
if gas_status == "DANGER":
red_light.value(1)
system_status = "GAS DANGER"
# TOO CLOSE OBJECT (RED LED)
elif dist_status == "TOO CLOSE":
red_light.value(1)
system_status = "OBJECT DANGER"
# VEHICLE DETECTED - (LIGHT ON)
elif dist_status == "VEHICLE":
tunnel_light.value(1)
system_status = "VEHICLE PRESENT"
else:
system_status = "ENERGY SAFE"
tunnel_light.value(0)
red_light.value(0)
print("Distance:", dist_status,
"| Gas:", gas_status,
"| System:", system_status)
sleep(1)