import network
import time
from machine import Pin, PWM
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-esp32-buzzer-mqtt"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "buzzer-activate"
buzzer_pins = [12, 27, 21, 15]
buzzer_pwm = [PWM(Pin(pin), freq=1000, duty=0) for pin in buzzer_pins]
current_buzzer = None
last_buzzer_activation_time = 0
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 buzzer_activate(buzzer_number):
global current_buzzer, last_buzzer_activation_time
# Check if enough time has passed since the last buzzer activation
current_time = time.time()
if (current_time - last_buzzer_activation_time) < 5:
print("Not enough time has passed since the last buzzer activation.")
return
# Activate the corresponding buzzer
if current_buzzer is not None:
current_buzzer.value(0)
buzzer_pin = Pin(buzzer_pins[buzzer_number - 1], Pin.OUT)
buzzer_pin.value(1)
current_buzzer = buzzer_pin
# Update the last buzzer activation time
last_buzzer_activation_time = current_time
def buzzer_message_received(topic, message):
buzzer_number = int(message.decode("utf-8"))
if 1 <= buzzer_number <= 4:
print("Received from MQTT topic: {} - activating Buzzer {}".format(topic.decode("utf-8"), buzzer_number))
buzzer_activate(buzzer_number)
else:
print("Invalid buzzer number! Must be between 1 and 4.")
# Set up buzzer pins
for buzzer_pin in buzzer_pins:
Pin(buzzer_pin, Pin.OUT, value=0)
# Set up MQTT client
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(buzzer_message_received)
connect_to_mqtt_broker()
try:
while 1:
client.wait_msg()
finally:
client.disconnect()