import network
import time
import machine
import math
from umqtt.simple import MQTTClient
SSID = "Wokwi-GUEST"
PASSWORD = ""
MQTT_BROKER = "broker.hivemq.com"
MQTT_CLIENT_ID = "wokwi-esp32"
TOPIC_SUB = b"esp32/Hazem"
TOPIC_PUB = b"esp32/Omar"
BETA = 3950
ADC_MAX = 1023
adc = machine.ADC(machine.Pin(35))
adc.atten(machine.ADC.ATTN_11DB)
adc.width(machine.ADC.WIDTH_10BIT)
relay = machine.Pin(14, machine.Pin.OUT)
def connect_wifi():
print("Connecting to Wi-Fi...")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(0.1)
print("Connected:", wlan.ifconfig())
def mqtt_callback(topic, msg):
print("Topic:", topic, "Message:", msg)
if topic == TOPIC_SUB:
if msg == b'on':
relay.value(1)
print("LED: On")
elif msg == b'off':
relay.value(0)
print("LED: Off")
def read_temperature():
analog = adc.read()
celsius = 1/(math.log(1/(1023. / analog - 1)) / BETA + 1.0 / 298.15) - 273.15
print("Temperature: {:.2f} °C".format(celsius))
time.sleep(5)
return celsius
def main():
connect_wifi()
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(TOPIC_SUB)
print("MQTT connected")
while True:
try:
client.check_msg()
celsius = read_temperature()
client.publish(TOPIC_PUB, str(celsius).encode())
print("Temperature: {:.2f} °C".format(celsius))
except Exception as e:
print("Error:", e)
time.sleep(5)
main()