import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
MQTT_CLIENT_ID = "micropython-button-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "buzzer-activate"
BUTTON_PINS = [23, 22, 2, 15]
button_pins = [Pin(pin, Pin.IN, Pin.PULL_DOWN) for pin in BUTTON_PINS]
last_states = [button.value() for button in button_pins]
last_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 on_message(topic, msg):
print("Received message on topic {}: {}".format(topic, msg))
def send_button_press(button_number):
message = "{}".format(button_number)
print("Send message: {}".format(message))
client.publish(MQTT_TOPIC, message)
def button_press(button, last_state, button_number):
global last_activation_time
current_state = button.value()
current_time = time.time()
if (current_time - last_activation_time) < 5:
print("Not enough time has passed since the last buzzer activation.")
return
else:
if last_state == 0 and current_state == 1:
send_button_press(button_number)
return current_state
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(on_message)
connect_to_mqtt_broker()
try:
while True:
for i, button in enumerate(button_pins):
last_states[i] = button_press(button, last_states[i], i + 1)
client.check_msg()
time.sleep(0.1)
finally:
client.disconnect()