print("Hello, ESP32!")
"""
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 Publish, set the Topic to "mkz/home/kitchen/light/state"
4. in the Message field type [255, 0, 0] (or any other color RGB value)
5. click "Publish"
6. Open MIT App Inverter. Run MQTTKitchenLight
7. Download Android Apps : https://play.google.com/store/apps/details?id=edu.mit.appinventor.aicompanion3&hl=en-MY
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
from utime import sleep_ms # "utime" is an optimized subset version of the CPython time module
pixels = NeoPixel(Pin(13), 16)
pixels.fill((0, 0, 0))
pixels.write()
led = Pin(2, Pin.OUT) # create output pin on GPIO2
def mqtt_message(topic, msg):
print("Incoming message:", msg)
try:
msg = ujson.loads(msg)
pixels.fill((msg[0], msg[1], msg[2]))
pixels.write()
if msg[3] == 0:
#if msg == b'off':
led.value(0)
print('LED is now OFF')
elif msg[3] == 1:
#elif msg == b'on':
led.value(1)
print('LED is now ON')
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("mkz/home/kitchen/light/state")
print("Connected!")
while True:
client.wait_msg()