import network
import time
from umqtt.simple import MQTTClient
from machine import Pin, PWM, time_pulse_us
# WiFi Config
SSID = 'Wokwi-GUEST'
PASSWORD = ''
# MQTT Config
BROKER = 'broker.emqx.io'
PORT = 1883
TOPIC_PUB = b"distance"
TOPIC_SUB = b"door"
CLIENT_ID = b"publisher-door"
# Ultrasonic Pins
TRIG = Pin(5, Pin.OUT)
ECHO = Pin(18, Pin.IN)
# Servo Motor
servo = PWM(Pin(15), freq=50)
# Connect WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("š Connecting WiFi...", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nā
Connected:", wlan.ifconfig())
# Servo Control
def set_servo(angle):
duty = int(((angle / 180) * 102) + 26) # map 0ā180° to duty cycle
servo.duty(duty)
# Distance Measurement
def get_distance():
TRIG.value(0)
time.sleep_us(2)
TRIG.value(1)
time.sleep_us(2)
TRIG.value(0)
duration = time_pulse_us(ECHO, 1, 30000)
distance = (duration / 2) * 0.0343
return distance
# Callback for subscriber messages
def message_callback(topic, msg):
command = msg.decode()
print(f"š© Command received: {command}")
if command == "CLOSE":
print(" Door closed")
set_servo(0)
elif command == "OPEN":
print("Opening Door")
set_servo(90)
time.sleep(0)
# Main loop
def main():
client = MQTTClient(CLIENT_ID, BROKER, PORT)
client.set_callback(message_callback)
client.connect()
print("ā
Connected to MQTT Broker")
client.subscribe(TOPIC_SUB)
try:
while True:
# Publish distance
dist = get_distance()
client.publish(TOPIC_PUB, str(dist))
print(f"š¤ Published Distance: {dist:.2f} cm")
# Check incoming messages
client.check_msg()
time.sleep(1)
finally:
client.disconnect()
# Run
connect_wifi()
main()