import network
import time
from machine import Pin, ADC
from umqtt.simple import MQTTClient
import math
# WiFi and MQTT configuration
SSID = 'Wokwi-GUEST'
PASSWORD = ''
MQTT_SERVER = 'broker.emqx.io'
MQTT_PORT = 1883
CLIENT_ID = 'esp-main'
TEMP_TOPIC = 'data/temp'
ACTUATOR_TOPIC = 'control/actuator'
# Configure ADC for temperature sensor
adc = ADC(Pin(34))
adc.width(ADC.WIDTH_12BIT)
adc.atten(ADC.ATTN_11DB)
def connect_wifi():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('Connecting to WiFi...')
sta_if.active(True)
sta_if.connect(SSID, PASSWORD)
while not sta_if.isconnected():
time.sleep(1)
print('WiFi connected, IP:', sta_if.ifconfig()[0])
def get_temperature():
BETA = 3950 # Beta parameter for temperature calculation
analog_value = adc.read()
celsius = 1 / (math.log(1 / (4095. / analog_value - 1)) / BETA + 1.0 / 298.15) - 273.15
return max(min(celsius, 80), -24) # Clamp value between -24 and 80
def mqtt_connect():
client = MQTTClient(CLIENT_ID, MQTT_SERVER, port=MQTT_PORT)
client.connect()
print('Connected to MQTT broker')
return client
def main():
connect_wifi()
client = mqtt_connect()
while True:
temp = get_temperature()
try:
print("Publishing temperature:", temp)
client.publish(TEMP_TOPIC, str(temp))
except Exception as e:
print('Failed to publish message:', e)
client = mqtt_connect()
time.sleep(5)
if __name__ == "__main__":
main()