import network
import time
from machine import Pin, PWM
from umqtt.simple import MQTTClient
# WiFi configuration
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
# MQTT configuration
MQTT_BROKER = 'mqtt-dashboard.com'
MQTT_CLIENT_ID = 'esp32_servo_controller'
MQTT_TOPIC = 'esp32/servo'
# Servo configuration
SERVO_PIN = 33
SERVO_MIN_DUTY = 40 # Minimum duty cycle for 0 degrees (this value may need adjustment for your servo)
SERVO_MAX_DUTY = 115 # Maximum duty cycle for 180 degrees (this value may need adjustment for your servo)
# Function to connect to WiFi
def connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print('WiFi connected!')
# Function to connect to MQTT broker
def connect_mqtt():
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(on_message)
client.connect()
client.subscribe(MQTT_TOPIC)
print('Connected to MQTT broker and subscribed to topic!')
return client
# Function to handle incoming MQTT messages
def on_message(topic, msg):
try:
angle = int(msg)
if 0 <= angle <= 180:
set_servo_angle(angle)
else:
print('Received angle out of range:', angle)
except ValueError:
print('Invalid message:', msg)
# Function to set the servo angle
def set_servo_angle(angle):
duty = SERVO_MIN_DUTY + (SERVO_MAX_DUTY - SERVO_MIN_DUTY) * angle // 180
servo.duty(duty)
print('Servo angle set to:', angle)
# Initialize servo motor
servo = PWM(Pin(SERVO_PIN), freq=50)
set_servo_angle(90) # Initial position
# Connect to WiFi
connect_wifi(WIFI_SSID, WIFI_PASSWORD)
# Connect to MQTT broker
mqtt_client = connect_mqtt()
# Main loop to check for MQTT messages
try:
while True:
mqtt_client.check_msg()
time.sleep(1)
except KeyboardInterrupt:
print('Disconnected from MQTT broker')
mqtt_client.disconnect()