import network
import ujson
import time
from machine import SoftI2C, Pin, PWM
from utime import sleep
from dht import DHT22
from umqtt.simple import MQTTClient
import ssd1306
MQTT_CLIENT_ID = "micropython-weather"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC1 = "temperature13"
MQTT_TOPIC2 = "humidity13"
MQTT_TOPIC3 = "grisha13"
sensor = DHT22(Pin(23))
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
RED_LED = Pin(27, Pin.OUT)
GREEN_LED = Pin(13, 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 = 'fffeffgagaaaefeffcffadh'
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!")
state = 0
def sub_cb(topic, msg):
global state
print((topic, msg))
if msg == b'play':
for tone, length in zip(melody, rhythm):
buzzer.freq(tones[tone])
buzzer.duty(512)
time.sleep(tempo/length)
buzzer.duty(0)
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_TOPIC3)
print("Connected!")
while True:
sensor.measure()
temp = sensor.temperature()
humid = sensor.humidity()
tempmin = 18
tempmax = 25
humidmin = 20
humidmax = 60
print(f"Temperature: {sensor.temperature()} \nHumidity: {sensor.humidity()}")
if (temp<tempmin) :
RED_LED.off()
elif (temp>tempmax) :
RED_LED.on()
if (humid<humidmin) :
GREEN_LED.on()
elif (humid>humidmax) :
GREEN_LED.off()
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=str(temp)
humid=str(humid)
client.publish(MQTT_TOPIC1, temp)
client.publish(MQTT_TOPIC2, humid)
sleep(2)
client.check_msg()