"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
"""from machine import Pin, PWM, I2C
from time import sleep
from dht import DHT22
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Khai báo cảm biến DHT22
dht_sensor = DHT22(Pin(4))
# Khai báo LED và Buzzer
led = Pin(25, Pin.OUT)
buzzer = PWM(Pin(26), freq=2000, duty_u16=0) # Buzzer ban đầu không kêu
# Khai báo I2C cho LCD 2004
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 4, 20)
# Hàm hiển thị nhiệt độ, độ ẩm lên LCD
def display_temp_humidity(temp, hum):
lcd.move_to(0, 0)
lcd.putstr("Nhiet do: {:.1f} C ".format(temp)) # Thêm dấu cách xóa ký tự thừa
lcd.move_to(0, 1)
lcd.putstr("Do am : {:.1f} % ".format(hum))
lcd.move_to(0, 2)
lcd.putstr("Canh bao: " + ("Nhiet do cao! " if temp > 25 else "Binh thuong "))
# Vòng lặp chính
while True:
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
display_temp_humidity(temp, hum)
if temp > 25:
# LED nhấp nháy và buzzer kêu nhanh
for _ in range(5):
led.on()
buzzer.duty_u16(30000) # Bật buzzer
sleep(0.2)
led.off()
buzzer.duty_u16(0) # Tắt buzzer
sleep(0.2)
else:
led.off()
buzzer.duty_u16(0) # Tắt buzzer hoàn toàn
sleep(2)
except Exception as e:
print("Lỗi: ", e)
"""
from machine import Pin, PWM, I2C
from time import sleep
from dht import DHT22
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Khai báo cảm biến DHT22
dht_sensor = DHT22(Pin(4))
# Khai báo LED và Buzzer
led = Pin(25, Pin.OUT)
buzzer = PWM(Pin(26), freq=2000, duty_u16=0) # Buzzer ban đầu không kêu
# Khai báo I2C cho LCD 2004
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 4, 20)
while True:
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
# Hiển thị nhiệt độ & độ ẩm lên LCD
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr(f"Nhiệt độ: {temp:.1f} C")
lcd.move_to(0, 1)
lcd.putstr(f"Độ ẩm: {hum:.1f} %")
# Nếu nhiệt độ > 25 độ C
if temp > 25:
for _ in range(5):
led.on()
buzzer.on()
time.sleep(0.1)
led.off()
buzzer.off()
time.sleep(0.1)
else:
led.off()
buzzer.off()
time.sleep(2)
except Exception as e:
lcd.clear()
lcd.putstr("Lỗi cảm biến!")
print("Lỗi:", e)
time.sleep(2)