import network
import ujson
from neopixel import NeoPixel
from machine import Pin
from time import sleep
from umqtt.simple import MQTTClient
# LED Configuration
pixels = NeoPixel(Pin(13), 16)
# Color definitions (replace with your preferred colors if needed)
DEFAULT_COLOR = (255, 255, 255) # Choose your default color for "on" state
# MQTT Broker Parameters
MQTT_CLIENT_ID = "wokwi-neopixel"
MQTT_BROKER = "broker.hivemq.com"
MQTT_TOPIC = "wokwi-BASE" # Topic to publish to
# Message payloads for on/off states (replace if needed)
MSG_ON = "ON"
MSG_OFF = "OFF"
# Current LED state (initialize as off)
led_state = False
# Button configuration (replace with your button pin)
button_pin = Pin(12, Pin.IN) # Adjust the pin number for your button
print("Connecting to WiFi...", end="")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
sleep(0.5)
print(".", end="")
print("Done")
print("Connecting to MQTT...")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.connect()
print("Connected!")
# Define a function to publish the current LED state
def publish_led_state():
message = MSG_ON if led_state else MSG_OFF
client.publish(MQTT_TOPIC, message)
print("Published LED state:", message)
# Define a function to turn the LED on/off and publish the state
def set_led_state(state):
global led_state # Access the global variable
if state:
pixels.fill(DEFAULT_COLOR) # Set color for "on" state
pixels.write()
else:
pixels.fill((0, 0, 0)) # Turn off LEDs (black)
pixels.write()
led_state = state
publish_led_state() # Publish the updated state
# Initial LED state and publish (start off)
set_led_state(False)
# Main loop
last_button_state = False # Track previous button state for debouncing
while True:
# Read current button state
current_button_state = button_pin.value()
# Debounce the button press (optional)
if current_button_state != last_button_state and not current_button_state:
# Button press detected (rising edge)
led_state = not led_state # Toggle LED state
set_led_state(led_state)
last_button_state = current_button_state # Update last button state
sleep(0.01) # Adjust debounce time (optional)