import network
import ujson
import time
from machine import Pin, SoftI2C, PWM
from utime import sleep
import dht
import ssd1306
from umqtt.simple import MQTTClient
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_1 = "wokwi-temperature"
MQTT_TOPIC_2 = "wokwi-humidity"
MQTT_TOPIC_S = "wokwi-sounds"
sensor = dht.DHT22(Pin(23))
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
ledG = Pin(12, Pin.OUT)
ledR = Pin(13, Pin.OUT)
ledB = Pin(14, Pin.OUT)
ledG1 = Pin(26, Pin.OUT)
ledR1 = Pin(27, Pin.OUT)
ledB1 = Pin(25, Pin.OUT)
tempo = 5
tones = {
'a': 262,
'b': 294,
'c': 330,
'd': 349,
'e': 392,
'f': 440,
'g': 494,
'h': 523,
}
buzzer = PWM(Pin(15, Pin.OUT))
melody = 'abcdefgh'
rhythm = [10, 10, 10, 10, 10, 10, 10, 10]
buzzer.freq(1)
buzzer.duty(0)
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
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!")
def sub_cb(topic, msg):
global state
print((topic, msg))
if msg == b'on' or msg == b'On':
for tone, length in zip(melody, rhythm):
buzzer.freq(tones[tone])
buzzer.duty(512)
time.sleep(tempo/length)
elif msg == b"off" or msg == b'Off':
buzzer.deinit()
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_cb)
client.connect()
client.subscribe(MQTT_TOPIC_S)
print("Connected!")
prev_weather_1 = ""
prev_weather_2 = ""
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
message_1 = ujson.dumps(
sensor.temperature(),
)
message_2 = ujson.dumps(
sensor.humidity(),
)
if message_1 != prev_weather_1 or message_2 != prev_weather_2 :
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(message_1, message_2))
client.publish(MQTT_TOPIC_1, message_1)
client.publish(MQTT_TOPIC_2, message_2)
prev_weather_1 = message_1
prev_weather_2 = message_2
else:
print("No change")
oled.fill(0)
oled.show()
oled.text(f"Temp. : {sensor.temperature()} C", 0, 0)
oled.text(f"Humidity : {sensor.humidity():.1f}%", 0, 10)
oled.show()
temp = (sensor.temperature())
tempmin = 15
tempmax = 30
humid = (sensor.humidity())
humidmin = 20
humidmax = 65
if (temp<tempmin) :
ledG.off()
ledR.off()
ledB.on()
elif (temp>tempmax) :
ledR.on()
ledG.off()
ledB.off()
else :
ledR.off()
ledG.on()
ledB.off()
if (humid<humidmin) :
ledG1.on()
ledR1.on()
ledB1.off()
elif (humid>humidmax) :
ledR1.on()
ledG1.off()
ledB1.on()
else :
ledR1.off()
ledG1.on()
ledB1.off()
sleep(2)
client.check_msg()