import network
import ujson
from neopixel import NeoPixel
from machine import Pin, PWM
from time import sleep
from umqtt.simple import MQTTClient
# Create a PWM object on Pin 22
servo = PWM(Pin(22), freq=50)
# Create a NeoPixel object on Pin 18
pixels = NeoPixel(Pin(18), 16)
pixels.fill((0, 0, 0))
pixels.write()
def set_angle(angle):
# Convert the angle to duty cycle
duty = (int(((angle)/180 *2 + 0.5) / 20 * 1023))
# Set the duty cycle
servo.duty(duty)
def mqtt_message(topic, msg):
print("Incoming message:", msg)
try:
msg = ujson.loads(msg)
# Check if the message is for controlling the servo
if 'angle' in msg:
# Control the servo
set_angle(msg['angle'])
else:
# Control the NeoPixels
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("Lab3")
print("Connected!")
while True:
client.wait_msg()