"""
MicroPython IoT Weather Station with Servo Control
This MicroPython script transforms an IoT device into a weather station using a DHT22 temperature and humidity sensor. The weather conditions are measured and reported to an MQTT server. Additionally, it controls a servo motor based on the detected temperature, sweeping between 0 and 180 degrees when the temperature exceeds a specified threshold.
MQTT Server Parameters:
- Client ID: micropython-weather-demo
- Broker: broker.mqttdashboard.com
- User: [Your MQTT User] (if applicable)
- Password: [Your MQTT Password] (if applicable)
- Topic: wokwi-weather
Hardware Configuration:
- Servo connected to GPIO Pin 18
- DHT22 sensor connected to GPIO Pin 15
Temperature Threshold: 25.0 degrees Celsius
Instructions:
1. Connect the servo motor and DHT22 sensor to the designated GPIO pins.
2. Configure MQTT server parameters and WiFi credentials.
3. Upload and run this script on your MicroPython device.
4. Observe the simulated servo motion on temperature changes.
Author: Jorge A. Perales Saavedra
Date: 23/09/2023
"""
from machine import Pin, PWM
from utime import sleep, sleep_us
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
# Configuramos el pin al que estará conectado el servo
servo = PWM(Pin(18), freq=50)
sensor = dht.DHT22(Pin(15))
# Definimos estados
SERVO_STOPPED = 0
SERVO_MOVING = 1
# Inicializamos el estado
current_state = SERVO_STOPPED
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
time.sleep(2)
umbral_temperatura = 25.0
prev_weather = ""
while True:
print("Measuring weather conditions... ", end="")
try:
sensor.measure()
temperatura_actual = sensor.temperature()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print("no change")
# Cambiamos el estado según la temperatura
if temperatura_actual > umbral_temperatura and current_state == SERVO_STOPPED:
print("Temperatura superior al umbral, iniciando movimiento del servomotor")
current_state = SERVO_MOVING
# Manejamos el estado del servo
if current_state == SERVO_MOVING:
for i in range(1800, 8000):
servo.duty_u16(i)
sleep_us(1)
for i in range(8000, 1800, -1):
servo.duty_u16(i)
sleep_us(1)
sensor.measure()
temperatura_actual = sensor.temperature()
# Cambiamos el estado de nuevo si la temperatura baja
if temperatura_actual <= umbral_temperatura:
print("Temperatura por debajo del umbral, deteniendo el servo")
current_state = SERVO_STOPPED
except OSError as e:
print("Error en la medición:", e)
# Manejar el error ECONNRESET reconectando el cliente MQTT
try:
client.connect()
print("Reconectado al servidor MQTT.")
except OSError as reconnect_error:
print("Error al reconectar al servidor MQTT:", reconnect_error)
time.sleep(2) # Esperar antes de intentar nuevamente
continue
time.sleep(1)