import network
import time
from machine import Pin, ADC
from umqtt.simple import MQTTClient
import math
ssid = "Wokwi-GUEST"
password = ""
mqtt_server = "broker.hivemq.com"
client_id = "esp32-client"
topic_temp = b"esp32/temp"
topic_relay = b"esp32/relay/control"
relay_pin = Pin(19, Pin.OUT)
temp_sensor = ADC(Pin(34))
temp_sensor.atten(ADC.ATTN_11DB) # full range (0 - 3.3V)
temp_sensor.width(ADC.WIDTH_12BIT) # 0-4095
# Connect to Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
print("Connecting to Wi-Fi", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nConnected to Wi-Fi")
# Read temperature using BETA formula
def read_temp():
BETA = 3950
analog = temp_sensor.read()
celsius = 1 / (math.log(1 / (4095 / analog - 1)) / BETA + 1 / 298.15) - 273.15
return round(celsius, 2)
# MQTT message handler
def mqtt_callback(topic, msg):
print("Received:", topic, msg)
if topic == topic_relay:
if msg == b"on":
relay_pin.on()
elif msg == b"off":
relay_pin.off()
# Connect and loop
connect_wifi()
client = MQTTClient(client_id, mqtt_server)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(topic_relay)
print("Connected to MQTT broker and subscribed to relay control.")
try:
while True:
temp = read_temp()
print("Temperature:", temp, "°C")
client.publish(topic_temp, str(temp))
if temp >= 30:
relay_pin.on()
print("Relay ON due to high temp")
else:
relay_pin.off() #
print("Relay OFF due to low temp")
client.check_msg()
time.sleep(10)
except KeyboardInterrupt:
print("Disconnected")
client.disconnect()