import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-motion-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-motion"
# Define the PIR sensor pin
pir_pin = Pin(4, Pin.IN) # D4 on ESP32
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!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
while True:
motion_value = pir_pin.value()
print("Motion value:", motion_value)
if motion_value == 1:
print("Motion detected!")
message = "Motion detected!"
else:
print("No motion")
message = "No motion"
client.publish(MQTT_TOPIC, message)
time.sleep(1)