"""
MicroPython MQTT NeoPixels Example for Wokwi.com
To control the pixels:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Public, set the Topic to "wokwi"
4. in the Message field type [255, 0, 0] (or any other color RGB value)
5. click "Publish"
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/315787266233467457
"""
import network
import ujson
from neopixel import NeoPixel
from machine import Pin
from time import sleep
from umqtt.simple import MQTTClient
pixels = NeoPixel(Pin(13), 16)
pixels.fill((0, 0, 0))
pixels.write()
def mqtt_message(topic, msg):
print("Incoming message:", msg)
try:
msg = ujson.loads(msg)
pixels.fill((msg[0], msg[1], msg[2]))
pixels.write()
except Exception as e:
print("Error:", e)
print("Connecting to WiFi...", end="")
import network
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("wokwi1", "broker.hivemq.com")
client.set_callback(mqtt_message)
client.connect()
client.subscribe("wokwi")
print("Connected!")
while True:
client.wait_msg()