import dht
import network
from machine import Pin
import time
import urequests as requests
import uasyncio as asyncio
# Khai báo cảm biến DHT22
d = dht.DHT22(Pin(16, Pin.IN))
led = Pin(26, Pin.OUT)
pir = Pin(5, Pin.IN)
# Kết nối đến WiFi
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!")
# Đọc dữ liệu từ cảm biến
async def control_dht():
while True:
d.measure()
t = d.temperature() # Nhiệt độ
h = d.humidity() # Độ ẩm
print("Temperature: {}°C, Humidity: {}%".format(t, h))
#gui du lieu len thingspeak HTTP - GET
try:
res = requests.get(url=f'https://api.thingspeak.com/update?api_key=U08LOKNVFG3PKV7S&field1={t}&field2={h}')
except:
print("Error!!!")
await asyncio.sleep(1)
async def control_pir():
while True:
if pir():
print('Motion detected!')
led.on()
await asyncio.sleep(1)
led.off()
if not pir():
print('Motion stopped')
loop = asyncio.get_event_loop()
loop.create_task(control_pir())
loop.create_task(control_dht())
loop.run_forever()