"""
MicroPython IoT Weather Station Example for Wokwi.com
This example reads temperature and humidity from a DHT22 sensor, controls an RGB LED
based on the temperature, and responds to MQTT commands to turn on/off a specific LED.
"""
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "Ivan"
MQTT_BROKER = "mqtt-dashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "topic/D'GRIM/Ivan/data_sensor"
SUB_MQTT_TOPIC = "topic/D'GRIM/Ivan/aktuasi_led"
# LED Pins
led = Pin(5, Pin.OUT) # Controlled by MQTT messages
ledR = Pin(33, Pin.OUT) # Red LED
ledG = Pin(32, Pin.OUT) # Green LED
ledB = Pin(25, Pin.OUT) # Blue LED
# DHT22 Sensor
sensor1 = dht.DHT22(Pin(2))
# Fungsi aktuasi LED dari pesan MQTT
def aktuasi_led(topic, msg):
try:
pesan = msg.decode('utf-8') # Decode pesan menjadi string
input_command = pesan.lower() # Ubah ke huruf kecil untuk mempermudah perbandingan
if input_command == "on":
print("LED Pin 5 ON")
led.on() # Nyalakan LED di pin 5
elif input_command == "off":
print("LED Pin 5 OFF")
led.off() # Matikan LED di pin 5
else:
print("Message not recognized: ", pesan)
except ValueError:
print("Failed to decode, please try again")
# WIFI Connection
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!")
# MQTT Server connection
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(aktuasi_led) # Set callback untuk menerima pesan
client.connect()
client.subscribe(SUB_MQTT_TOPIC) # Berlangganan ke topik SUB_MQTT_TOPIC
print("Connected to MQTT server!")
# Build the message in JSON format and send the message only if there is a change
prev_weather = ""
while True:
print("Measuring weather conditions... ", end="")
sensor1.measure()
temperature = sensor1.temperature()
humidity = sensor1.humidity()
# Control LED RGB based on temperature
if temperature < 10:
ledB.value(1) # Blue ON
ledG.value(0) # Green OFF
ledR.value(0) # Red OFF
elif 10 <= temperature <= 30:
ledB.value(0) # Blue OFF
ledG.value(1) # Green ON
ledR.value(0) # Red OFF
else:
ledB.value(0) # Blue OFF
ledG.value(0) # Green OFF
ledR.value(1) # Red ON
# Publish sensor data if changed
message = ujson.dumps({
"temp1": temperature,
"humidity1": humidity,
})
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message) # Publish data ke MQTT
prev_weather = message
else:
print("No change")
# Check for new MQTT messages
client.check_msg() # Periksa pesan masuk dari broker MQTT
time.sleep(1)