import network
import time
import machine
import math
from machine import Pin, ADC
from umqtt.simple import MQTTClient
# --- Configuration ---
SSID = "Wokwi-GUEST"
PASSWORD = ""
MQTT_BROKER = "broker.hivemq.com"
TOPIC_TEMP = "esp32/temp"
TOPIC_RELAY_CMD = "esp32/relay_cmd"
TOPIC_THRESHOLD = "esp32/set_threshold"
# --- Hardware Setup ---
relay = Pin(21, Pin.OUT)
adc = ADC(Pin(34))
adc.width(ADC.WIDTH_10BIT)
adc.atten(ADC.ATTN_11DB)
# --- Variables ---
mode = "manual" # can be "manual" or "auto"
threshold = 30 # default temperature threshold in °C
# --- WiFi Connection ---
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.5)
print("Connected to Wi-Fi:", wlan.ifconfig())
# --- MQTT Callback ---
def mqtt_callback(topic, msg):
global mode, threshold
topic = topic.decode()
msg = msg.decode()
print("Received:", topic, msg)
if topic == TOPIC_RELAY_CMD:
mode = "manual"
if msg == "on":
relay.value(1)
print("Relay turned ON (manual)")
elif msg == "off":
relay.value(0)
print("Relay turned OFF (manual)")
elif topic == TOPIC_THRESHOLD:
mode = "auto"
try:
threshold = float(msg)
print("Threshold updated to:", threshold)
except:
print("Invalid threshold value!")
# --- Temperature Reading ---
def read_temperature():
BETA = 3950
value = adc.read()
if value == 0:
return 0
celsius = 1 / (math.log(1 / (1023. / value - 1)) / BETA + 1.0 / 298.15) - 273.15
return round(celsius, 2)
# --- Main Program ---
def main():
connect_wifi()
client = MQTTClient("esp32_client", MQTT_BROKER)
client.set_callback(mqtt_callback)
client.connect()
print("MQTT Connected!")
client.subscribe(TOPIC_RELAY_CMD)
client.subscribe(TOPIC_THRESHOLD)
while True:
temp = read_temperature()
print("Temperature:", temp, "°C")
# Publish temperature
client.publish(TOPIC_TEMP, str(temp))
# Auto mode logic
if mode == "auto":
if temp > threshold:
relay.value(1)
print("Relay ON (auto)")
else:
relay.value(0)
print("Relay OFF (auto)")
# Check MQTT messages
client.check_msg()
time.sleep(2)
# --- Run ---
main()