"""
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
LCD (20x4, I2C): VCC vào 5V ESP32, GND vào GND Esp32,
SDA vào esp21, SCL vào esp22.
DHT22: VCC vào 3.3V esp32, SDA vào esp4, GND vào GND esp32.
Buzzer(2 chân): chân âm vào GND ESP32, chân dương vào esp27.
LED RGB: Chân GND (Cathode chung) vào GND ESP32,
Chân R (Red - Đỏ) vào esp25,
Chân G (Green - Xanh lá) vào esp26,
Chân B (Blue - Xanh dương) vào esp32
"""
from machine import Pin, I2C
import dht
import time
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Cấu hình I2C cho LCD
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 4, 20) # Địa chỉ I2C LCD là 0x27
# Cấu hình cảm biến DHT22
dht_sensor = dht.DHT22(Pin(4))
# Cấu hình còi Buzzer
buzzer = Pin(27, Pin.OUT)
# Cấu hình LED RGB (Cathode chung)
led_red = Pin(25, Pin.OUT)
led_green = Pin(26, Pin.OUT)
led_blue = Pin(32, Pin.OUT)
def set_led_color(r, g, b):
""" Điều khiển LED RGB với giá trị 1 (bật) hoặc 0 (tắt) """
led_red.value(r)
led_green.value(g)
led_blue.value(b)
while True:
try:
dht_sensor.measure() # Đọc dữ liệu từ DHT22
temperature = dht_sensor.temperature() # Đọc nhiệt độ (°C)
humidity = dht_sensor.humidity() # Đọc độ ẩm (%)
# Hiển thị lên LCD
lcd.clear()
lcd.putstr("Nhiet do: {:.1f} C".format(temperature))
lcd.move_to(0, 1)
lcd.putstr("Do am: {:.1f} %".format(humidity))
# Điều khiển buzzer nếu nhiệt độ > 30°C
if temperature > 30:
for _ in range(3): # Bật còi nhanh 3 lần
buzzer.value(1)
time.sleep(0.1)
buzzer.value(0)
time.sleep(0.1)
# Điều khiển LED RGB
if 23 <= temperature <= 28:
set_led_color(0, 0, 1) # Xanh dương
elif 29 <= temperature <= 34:
set_led_color(0, 1, 0) # Xanh lá
elif 35 <= temperature <= 40:
set_led_color(1, 0, 0) # Đỏ
else:
set_led_color(0, 0, 0) # Tắt LED nếu ngoài khoảng này
except Exception as e:
lcd.clear()
lcd.putstr("Loi doc cam bien!")
print("Lỗi:", e)
time.sleep(2) # Đợi 2 giây trước khi đo lại