from machine import Pin, ADC, SoftI2C
from time import sleep
import ssd1306
# === Traffic Light LEDs ===
red_A = Pin(13, Pin.OUT)
green_A = Pin(12, Pin.OUT)
red_B = Pin(14, Pin.OUT)
green_B = Pin(27, Pin.OUT)
# === Potentiometer for Distance Simulation ===
pot = ADC(Pin(34))
pot.atten(ADC.ATTN_11DB) # Set to full range 0–4095
# === OLED Setup ===
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# === Function: Simulate Distance (500m → 0m) ===
def get_distance_from_pot():
pot_value = pot.read()
distance = 500 - (pot_value / 4095) * 500
return distance
# === Function: Update OLED Display ===
def update_oled(distance, message):
oled.fill(0)
oled.text("AmbulanceMonitor", 0, 0)
oled.text("Distance: {} m".format(int(distance)), 0, 20)
oled.text("Status:", 0, 40)
oled.text(message, 60, 40)
oled.show()
# === Function: Traffic Light Logic ===
def update_traffic_lights(near, distance):
if near:
print("\n🚨 Ambulance Approaching (<200m)")
update_oled(distance, "NEAR ")
red_A.off()
green_A.on()
red_B.on()
green_B.off()
sleep(60)
print("⏱️ 1 minute passed. Resetting traffic lights.")
else:
print("\n✅ Normal traffic flow")
update_oled(distance, "NORMALFLOW")
# Reset to normal state
red_A.on()
green_A.off()
red_B.off()
green_B.on()
# === Set Initial State ===
red_A.on()
green_A.off()
red_B.off()
green_B.on()
# === Main Loop ===
while True:
distance = get_distance_from_pot()
print("📍 Distance to light:", round(distance, 2), "m")
if distance < 200:
update_traffic_lights(True, distance)
else:
update_traffic_lights(False, distance)
sleep(5)