from machine import Pin, SoftI2C
from i2c_lcd import I2cLcd
import time, network
from umqtt.simple import MQTTClient
import random
MQTT_BROKER = "broker.hivemq.com"
CLIENT_ID = "esp32_publisher"
TOPIC = "iot/road_monitor"
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=100000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
green_led = Pin(14, Pin.OUT)
yellow_led = Pin(12, Pin.OUT)
red_led = Pin(27, Pin.OUT)
buzzer = Pin(26, Pin.OUT)
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect("YOUR_WIFI_SSID", "YOUR_WIFI_PASSWORD")
while not sta.isconnected():
time.sleep(1)
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client.connect()
while True:
distance = random.uniform(5, 200)
motion = random.choice([0, 1])
light = random.randint(500, 2500)
temp = random.randint(20, 35)
hum = random.randint(40, 70)
error_flag = 0
payload = {
"distance": distance,
"motion": motion,
"light": light,
"temp": temp,
"hum": hum,
"error": error_flag
}
client.publish(TOPIC, str(payload))
lcd.clear()
if motion == 0:
green_led.off(); yellow_led.off(); red_led.off(); buzzer.off()
lcd.putstr("NO VEHICLE")
lcd.move_to(0,1); lcd.putstr("ROAD CLEAR")
else:
if distance > 150:
green_led.on(); yellow_led.on(); red_led.off(); buzzer.off()
lcd.putstr("INTERMEDIATE")
elif distance > 25:
green_led.on(); yellow_led.off(); red_led.off(); buzzer.off()
lcd.putstr("FAR AWAY")
elif distance > 10:
green_led.off(); yellow_led.on(); red_led.off(); buzzer.off()
lcd.putstr("NEAR ZONE")
else:
green_led.off(); yellow_led.off(); red_led.on(); buzzer.on()
lcd.putstr("DANGER")
time.sleep(2)