import network
import time
from machine import Pin, I2C
import dht
import ujson
from umqtt.simple import MQTTClient
from i2c_lcd import I2cLcd
# ========= WiFi =========
SSID = 'Wokwi-GUEST'
PASSWORD = ''
# ========= MQTT =========
MQTT_CLIENT_ID = "esp32-weather-ir"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "wokwi-weather"
# ========= DHT =========
dht_sensor = dht.DHT22(Pin(15))
# ========= IR =========
ir = Pin(4, Pin.IN)
# ========= LCD =========
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
lcd = I2cLcd(i2c, 0x27, 2, 16)
# ========= WiFi =========
lcd.putstr("Connecting WiFi")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(SSID, PASSWORD)
while not sta_if.isconnected():
pass
lcd.clear()
lcd.putstr("WiFi Connected")
time.sleep(1)
lcd.clear()
# ========= MQTT =========
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.connect()
lcd.putstr("MQTT Connected")
time.sleep(1)
lcd.clear()
# ========= IR Function =========
def read_nec():
while ir.value() == 1:
pass
while ir.value() == 0:
pass
while ir.value() == 1:
pass
data = 0
for i in range(32):
while ir.value() == 0:
pass
start = time.ticks_us()
while ir.value() == 1:
pass
duration = time.ticks_diff(time.ticks_us(), start)
if duration > 1000:
data |= (1 << i)
return data
mode = "main"
last_mode = ""
prev_weather = ""
last_update = 0
# ========= Main Loop =========
while True:
now = time.ticks_ms()
# ===== تحديث القراءة كل 2 ثانية =====
if time.ticks_diff(now, last_update) > 2000:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
# عرض فقط لو المود اتغير
if mode != last_mode:
lcd.clear()
if mode == "main":
lcd.move_to(0, 0)
lcd.putstr("Temp: {:.1f}C".format(temp))
lcd.move_to(0, 1)
lcd.putstr("Hum : {:.1f}%".format(hum))
elif mode == "temp":
lcd.putstr("Temperature")
lcd.move_to(0,1)
lcd.putstr(str(temp) + " C")
elif mode == "hum":
lcd.putstr("Humidity")
lcd.move_to(0,1)
lcd.putstr(str(hum) + " %")
last_mode = mode
# ===== MQTT =====
message = ujson.dumps({
"temp": temp,
"humidity": hum
})
if message != prev_weather:
client.publish(MQTT_TOPIC, message)
prev_weather = message
last_update = now
# ===== قراءة الريموت =====
if ir.value() == 0:
code = read_nec()
print(hex(code))
if code == 0x9768ff00: # زر 1
mode = "temp"
elif code == 0xcf30ff00: # زر 2
mode = "hum"
elif code == 0xfd02ff00: # OK
mode = "main"
time.sleep(0.4)
time.sleep(0.05)