from machine import Pin, ADC, time_pulse_us, I2C
from ssd1306 import SSD1306_I2C
from time import sleep, sleep_us
# Important Variables
system_status = "ENERGY SAVE"
w = 128
h = 64
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
oled = SSD1306_I2C(w, h, i2c)
# Initializing sensors
trig = Pin(12, Pin.OUT)
echo = Pin(14, Pin.OUT)
gas = ADC(Pin(34))
gas.atten(ADC.ATTN_11DB) # Give me the maximum range in microcontroller for this sensor in ESP32 (0 - 4095)
ldr = ADC(Pin(35))
ldr.atten(ADC.ATTN_11DB) # Give me the maximum range in microcontroller for this sensor in ESP32 (0 - 4095)
# Initializing LEDs
tunnel = Pin(4, Pin.OUT)
red = Pin(15, Pin.OUT)
# Thresholds
v_dist = 30
d_dist = 15
gas_limit = 2000
light_limit = 1000
# Functions
# Distance function
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) # This nly accepts the duration from 1 to 30000 us
if duration < 0:
return None
else:
return (duration * 0.0343) / 2 # Distance return
def distance_state(d):
# Distance checker
if d is None:
return "NO SIGNAL!"
elif d < d_dist:
return "TOO CLOSE!!"
elif d < v_dist:
return "VEHICLE"
else:
return "CLEAR"
def gas_state(g):
# Gas checker
if g > gas_limit:
return "DANGER!"
else:
return "SAFE"
def light_threshold(l):
# Light checker
if l < light_limit:
return "BRIGHT"
else:
return "DARK"
# Main loop
while True:
distance = get_distance()
gas_value = gas.read()
light_value = ldr.read()
dist_status = distance_state(distance)
gas_status = gas_state(gas_value)
light_status = light_threshold(light_value)
# Detecting possible threats or vehicle entries
if gas_status == "DANGER!":
red.value(1)
system_status = "GAS DANGER"
elif dist_status == "TOO CLOSE!!":
red.value(1)
system_status = "OBJECT DANGER"
elif dist_status == "VEHICLE":
tunnel.value(1)
system_status = "VEHICLE PRESENT"
elif light_status == "DARK":
tunnel.value(1)
system_status = "DARK AREA"
else:
system_status = "POWER SAVING :)"
tunnel.value(0)
red.value(0)
oled.fill(0)
oled.text(f"Distance: {dist_status}", 0, 0)
oled.text(f"Gas: {gas_status}", 0, 10)
oled.text(f"Light: {light_status}", 0, 20)
oled.text(f"System: {system_status}", 0, 30)
sleep(0.5)
oled.show()
sleep(1)