from machine import Pin
import time
import dht
import asyncio
import random as rd
import network
from umqtt.simple import MQTTClient
# led
led = Pin(19, Pin.OUT)
# led1
led1 = Pin(21, Pin.OUT)
# motion
motion = Pin(25, Pin.IN)
# dht
d = dht.DHT22(Pin(12))
# 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!")
# Connect to MQTT
MQTT_CLIENT_ID = f"bkacad_{rd.randint(0, 1000000)}"
MQTT_BROKER = "broker.hivemq.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_SUB_TOPIC = "d04k14_bkacad_14186"
MQTT_PUB_TOPIC = "d04k14_bkacad_14186/data"
# 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(1)
else:
led.off()
await asyncio.sleep(1)
async def task2():
while True:
d.measure()
t = d.temperature() # Correct method name
h = d.humidity() # Correct method name
print(f"t = {t}, h = {h}")
# Publish the data
payload = f"{{'temperature': {t}, 'humidity': {h}}}"
client.publish(MQTT_PUB_TOPIC, payload)
await asyncio.sleep(5)
# Listen for messages from the broker
async def task3():
while True:
client.check_msg()
await asyncio.sleep(1)
# Main loop
loop = asyncio.get_event_loop()
loop.create_task(task1())
loop.create_task(task2())
loop.create_task(task3())
loop.run_forever()