from machine import Pin, SoftI2C
import network, time
from umqtt.simple import MQTTClient
from i2c_lcd import I2cLcd
from nec import NEC
MQTT_BROKER = "broker.hivemq.com"
CLIENT_ID = "esp32_receiver"
TOPIC = "iot/road_monitor"
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=100000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
indicator_led = Pin(2, Pin.OUT)
error_led = Pin(4, 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()
last_button = None
def ir_callback(data, addr, ctrl):
global last_button
last_button = data
ir = NEC(Pin(23, Pin.IN), ir_callback)
sensor_data = {}
def sub_cb(topic, msg):
global sensor_data
sensor_data = eval(msg)
client.set_callback(sub_cb)
client.subscribe(TOPIC)
button_codes = [0x1, 0x2, 0x3, 0x4]
index = 0
while True:
client.check_msg()
if sensor_data:
if sensor_data.get("error") == 1:
error_led.on()
else:
error_led.off()
ir.simulate_button(button_codes[index])
index = (index + 1) % len(button_codes)
lcd.clear()
if last_button == 0x1:
lcd.putstr("Distance:{:.1f}".format(sensor_data["distance"]))
indicator_led.on()
elif last_button == 0x2:
lcd.putstr("Motion:{}".format(sensor_data["motion"]))
indicator_led.on()
elif last_button == 0x3:
lcd.putstr("Light:{}".format(sensor_data["light"]))
indicator_led.on()
elif last_button == 0x4:
lcd.putstr("Temp:{}C".format(sensor_data["temp"]))
lcd.move_to(0,1)
lcd.putstr("Hum:{}%".format(sensor_data["hum"]))
indicator_led.on()
else:
indicator_led.off()
time.sleep(3)