import network
import time
from machine import Pin, ADC, PWM
from umqtt.simple import MQTTClient
import math
ssid = 'Wokwi-GUEST'
password = ''
mqtt_server = 'broker.emqx.io'
mqtt_port = 1883
client_id = 'esp-1'
temp_topic = 'temp'
adc = ADC(Pin(34))
adc.width(ADC.WIDTH_12BIT)
adc.atten(ADC.ATTN_11DB)
def connect_wifi():
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
pass
print('WiFi connected')
print('IP:', sta_if.ifconfig()[0])
def get_temperature():
BETA = 3950
analog_value = adc.read()
celsius = 1 / (math.log(1 / (4095. / analog_value - 1)) / BETA + 1.0 / 298.15) - 273.15
if celsius < -24:
celsius = -24
elif celsius > 80:
celsius = 80
return celsius
def mqtt_connect():
client = MQTTClient(client_id, mqtt_server, port=mqtt_port)
client.connect()
print('Connected to MQTT broker, subscribed to topic', temp_topic)
return client
def spin_servo(pos):
duty = int((pos * 102) / 180 + 20)
servo.duty(duty)
connect_wifi()
client = None
pos = 0
while True:
if client is None:
try:
client = mqtt_connect()
except Exception as e:
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(5)
continue
temp = get_temperature()
try:
print("Published: ", str(temp))
client.publish(temp_topic, str(temp))
except Exception as e:
print('Failed to publish message. Reconnecting...')
client = None
continue
try:
client.check_msg()
except Exception as e:
print('Failed to check for new messages. Reconnecting...')
client = None
continue
time.sleep(5)