from machine import Pin
import network
import time
import ujson
from umqtt.simple import MQTTClient
# =====================================================
# MQTT Configuration
# =====================================================
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = b"smart/curtain/system"
CLIENT_ID = "ESP32_BOARD2"
# =====================================================
# WiFi Connection
# =====================================================
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
print("Connecting to WiFi...")
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
time.sleep(0.2)
print("WiFi Connected!")
print(wifi.ifconfig())
# =====================================================
# Stepper Driver Pins (A4988)
# =====================================================
STEP_PIN = Pin(14, Pin.OUT)
DIR_PIN = Pin(12, Pin.OUT)
# =====================================================
# Stepper Configuration
# =====================================================
TOTAL_STEPS = 200 # 360 degrees
STEP_DELAY = 800 # microseconds
current_position = 0
target_position = 0
current_command = "NO_PRESS"
# =====================================================
# Generate One Step
# =====================================================
def one_step(direction):
DIR_PIN.value(direction)
STEP_PIN.value(1)
time.sleep_us(STEP_DELAY)
STEP_PIN.value(0)
time.sleep_us(STEP_DELAY)
# =====================================================
# MQTT Callback
# =====================================================
def mqtt_callback(topic, msg):
global target_position, current_command
try:
data = ujson.loads(msg)
current_command = data["state"]
print("---------------")
print("Recieved command: ", current_command)
if current_command == "OPEN":
target_position = TOTAL_STEPS
elif current_command == "CLOSED":
target_position = 0
elif current_command == "STOP":
target_position = current_position
except Exception as e:
print("Msg error: ", e)
# =====================================================
# MQTT Connection
# =====================================================
print("MQTT Connecting")
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe(MQTT_TOPIC)
print("MQTT Connected")
# =====================================================
# Main Loop
# =====================================================
while True:
# check mqtt msg
try:
client.check_msg()
except OSError:
print("MQTT Disconnected.....Reconnecting")
while True:
try:
client = MQTTClient(CLIENT_ID, MQTT_BROKER)
client,subscribe(MQTT_TOPIC)
print("MQTT Connected")
break
except:
time.sleep(1)
#open
if current_position < target_position :
one_step(1)
current_position +=1
print("Position: ", current_position)
# close
elif current_position > target_position:
one_step(0)
current_position -= 1
if current_position < 0:
current_position = 0
print("Position: ", current_position)
time.sleep_ms(1)