import network
import time
import machine
from umqtt.simple import MQTTClient
# Wi-Fi and MQTT details
SSID = "Wokwi-GUEST"
PASSWORD = ""
MQTT_BROKER = "broker.hivemq.com"
TOPIC_SUB = b"esp32/print"
TOPIC_PUB = b"esp32/temp"
# Pin setup
TEMP_SENSOR = machine.ADC(machine.Pin(34))
TEMP_SENSOR.atten(machine.ADC.ATTN_11DB) # Full range: 0-3.6V
RELAY = machine.Pin(19, 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.5)
print("Connected:", wlan.ifconfig())
def mqtt_callback(topic, msg):
print("Topic:", topic, "Message:", msg)
if msg == b'on':
RELAY.value(1)
print("Relay turned ON")
elif msg == b'off':
RELAY.value(0)
print("Relay turned OFF")
def read_temperature():
adc_val = TEMP_SENSOR.read()
voltage = adc_val * (3.3 / 4095) # Convert ADC reading to voltage
# Estimate temperature from voltage (simplified for NTC, not accurate)
temp_c = (voltage - 0.5) * 100 # Assuming LM35 or similar
return round(temp_c, 2)
def main():
connect_wifi()
client = MQTTClient("wokwi-esp32", MQTT_BROKER)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(TOPIC_SUB)
print("MQTT connected and subscribed to:", TOPIC_SUB)
last_sent = time.ticks_ms()
while True:
client.check_msg()
# Send temperature every 10 seconds
if time.ticks_diff(time.ticks_ms(), last_sent) > 10000:
temp = read_temperature()
client.publish(TOPIC_PUB, str(temp))
print("Published temperature:", temp, "°C")
last_sent = time.ticks_ms()
time.sleep(0.1)
main()