import network
from umqtt.simple import MQTTClient
from machine import Pin, PWM, ADC
import neopixel
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# MQTT Broker credentials
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_CLIENT_ID = "esp32_client"
MQTT_TOPIC_NEOPIXEL = b"neopixel"
MQTT_TOPIC_SERVO = b"servo"
# NeoPixel configuration
NUM_PIXELS = 10
NEOPIXEL_PIN = 5 # GPIO 5
# Servo configuration
SERVO_PIN = 2 # GPIO 2
# Connect to WiFi
def connect_to_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print("Connected to WiFi")
# Set up NeoPixel
np = neopixel.NeoPixel(Pin(NEOPIXEL_PIN, Pin.OUT), NUM_PIXELS)
# Set up Servo
servo = PWM(Pin(SERVO_PIN), freq=50)
# Connect to WiFi
connect_to_wifi(WIFI_SSID, WIFI_PASSWORD)
# MQTT message callback for NeoPixel
def on_message_neopixel(topic, message):
if topic == MQTT_TOPIC_NEOPIXEL:
color = tuple(map(int, message.split(b',')))
set_neopixel_color(color)
# MQTT message callback for Servo
def on_message_servo(topic, message):
if topic == MQTT_TOPIC_SERVO:
angle = int(message)
set_servo_angle(angle)
# Set NeoPixel color
def set_neopixel_color(color):
np[0] = color
np.write()
# Set Servo angle
def set_servo_angle(angle):
duty = int((angle / 180) * 1023)
servo.duty(duty)
# Connect to MQTT Broker
client = MQTTClient(client_id=MQTT_CLIENT_ID, server=MQTT_BROKER)
client.set_callback(on_message_neopixel)
client.connect()
client.subscribe(MQTT_TOPIC_NEOPIXEL)
# Listen for MQTT messages
while True:
client.check_msg()
# Cleanup
client.disconnect()