"""
https://www.jitbit.com/screensharing/#46866311263964993202999999821186
To control the pixels and servo:
1. Go to https://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. to control the servo, in the message field, type [180] (or any other value to control the servo)
6. Basically if you enter a list with 1 item it will control the servo, while 3 item will control the neopixel
7. click "Publish"
"""
import network
import ujson
from neopixel import NeoPixel
from machine import Pin,PWM
from time import sleep
from umqtt.simple import MQTTClient
# servo pin
servo = PWM(Pin(12), freq=50)
# neopixel pin
pixels = NeoPixel(Pin(13), 16)
pixels.fill((0, 0, 0))
pixels.write()
def move_servo(angle):
duty_cycle = int(50 + angle / 180 * 75)
servo.duty(duty_cycle)
def mqtt_message(topic, msg):
print("Incoming message:", msg)
try:
msg = ujson.loads(msg)
if (len(msg)<=1):
move_servo(msg[0]) # servo
else:
pixels.fill((msg[0], msg[1], msg[2])) # neopixel
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("lab3-iqbal") # use this for mqtt topic
print("Connected!")
while True:
client.wait_msg()