import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
MQTT_CLIENT_ID = "buzzerSound280405"
MQTT_BROKER = "mqtt-dashboard.com"
MQTT_TOPIC = "bells1"
buzzer1_pin = 26
buzzer2_pin = 13
buzzer3_pin = 17
buzzer4_pin = 4
buzzer1 = Pin(buzzer1_pin, Pin.OUT)
buzzer2 = Pin(buzzer2_pin, Pin.OUT)
buzzer3 = Pin(buzzer3_pin, Pin.OUT)
buzzer4 = Pin(buzzer4_pin, Pin.OUT)
def connect_to_wifi():
# Connect to Wi-Fi
print("Connecting to Wi-Fi", 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!")
def connect_to_mqtt_broker():
# Connect to HiveMQ MQTT broker
connect_to_wifi()
print("Connecting to MQTT server... ", end="")
client.connect()
print("Connected!")
client.subscribe(MQTT_TOPIC)
print("Subscribed to {}".format(MQTT_TOPIC))
def beep_buzzer(topic, message):
topic = topic.decode("utf-8")
message = message.decode("utf-8")
print("Received from MQTT topic: {} - message: {}".format(topic, message))
my_list = list(message)
if(int(message[0]) == 1):
buzzer1.on()
time.sleep_ms(5000)
buzzer1.off()
elif(int(message[0]) == 2):
buzzer2.on()
time.sleep_ms(5000)
buzzer2.off()
elif(int(message[0]) == 3):
buzzer3.on()
time.sleep_ms(5000)
buzzer3.off()
elif(int(message[0]) == 4):
buzzer4.on()
time.sleep_ms(5000)
buzzer4.off()
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(beep_buzzer)
connect_to_mqtt_broker()
try:
while 1:
client.wait_msg()
finally:
client.disconnect()