from machine import Pin
import time
# Thu vien bat dong bo
import uasyncio as asyncio
import dht
import network
import urequests as requests
# Khai bao 2 den
led = Pin(14, Pin.OUT)
# Chan cam bien
d = dht.DHT22(Pin(18))
# cam bien chuyen dong 16
motion = Pin(16, Pin.IN)
led_motion = Pin(2, Pin.OUT)
# Ket noi 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!")
# Tao bien luu trang thai wifi
is_connected = False
# Lay thong tin moi truong
async def get_env():
global is_connected
while True:
d.measure()
t = d.temperature() # nhiet do
h = d.humidity() # do am
print(t, h)
# Co ket noi internet moi day len thingspeak
if(is_connected):
# https://api.thingspeak.com/update?api_key=MZW05049NHHQGK9O&field1=40&field2=50
res = requests.get(url=f'http://api.thingspeak.com/update?api_key=MZW05049NHHQGK9O&field1={t}&field2={h}')
del res # giai phong bo nho
await asyncio.sleep(30)
async def status_led():
led_status = False
global is_connected
while True:
is_connected = sta_if.isconnected()
if(is_connected == True):
led.on()
else:
# Goi den ham -> reconnect wifi
if(led_status):
led.off()
else:
led.on()
led_status = not led_status
await asyncio.sleep(0.5)
async def detect_motion():
while True:
v = motion.value()
if(v == 1):
led_motion.on()
else:
led_motion.off()
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.create_task(status_led())
loop.create_task(detect_motion())
loop.create_task(get_env())
loop.run_forever()