from machine import Pin
import time
import dht
import asyncio
import random as rd
import network
from umqtt.simple import MQTTClient
led = Pin(12, Pin.OUT)
motion = Pin(27, Pin.IN)
led.on()
# Dht
d = dht.DHT22(Pin(26))
led1 = Pin(32, Pin.OUT)
led2 = Pin(18, Pin.OUT)
sensor = Pin(5, Pin.IN)
# Connect 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!")
# ket noi den MQTT
MQTT_CLIENT_ID = f'bkacad_{rd.randint(0, 1000000)}'
MQTT_BROKER = "broker.hivemq.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_SUB_TOPIC = "d04k14_bkacad14206_20032004"
# Callback
def sub_cb(topic, msg):
print(topic, msg)
if(msg == b'on'):
led1.on()
elif(msg == b'off'):
led1.off()
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_SUB_TOPIC)
print("Connected!")
async def task1():
while True:
v = motion.value()
if(v == 1):
led.on()
await asyncio.sleep(10)
else:
led.off()
await asyncio.sleep(0.5)
async def task2():
while True:
d.measure()
t = d.temperature()
h = d.humidity()
print(f"t = {t}, h = {h}")
await asyncio.sleep(180)
# Listen for messages from the broker
async def task3():
while True:
client.check_msg()
await asyncio.sleep(0.5)
async def task4():
while True:
v = sensor.value()
print (v)
time.sleep(1)
if( v == 1):
led2.on()
else:
led2.off()
await asyncio.sleep(5)
# Main loop
loop = asyncio.get_event_loop()
loop.create_task(task1())
loop.create_task(task2())
loop.create_task(task3())
loop.create_task(task4())
loop.run_forever()