import network
import time
import ujson
from machine import Pin
from umqtt.simple import MQTTClient
# =========================
# WIFI
# =========================
SSID = "Wokwi-GUEST"
PASSWORD = ""
# =========================
# THINGSBOARD
# =========================
THINGSBOARD_HOST = "thingsboard.cloud"
ACCESS_TOKEN = "yBa31inQF6yYOWLf0603"
CLIENT_ID = "3b9ac790-3347-11f1-b174-255c03e1b993"
# =====================
# STEPPER PINS
# =====================
STEP = Pin(14, Pin.OUT)
DIR = Pin(12, Pin.OUT)
# =====================
# WIFI
# =====================
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
print("Connecting WiFi...")
while not wifi.isconnected():
time.sleep(0.5)
print("WiFi Connected")
# =====================
# MOTOR FUNCTION
# =====================
def move_motor(steps, direction, delay_us=1000):
DIR.value(direction)
for _ in range(steps):
STEP.value(1)
time.sleep_us(delay_us)
STEP.value(0)
time.sleep_us(delay_us)
# =====================
# RPC CALLBACK
# =====================
def rpc_callback(topic, msg):
try:
data = ujson.loads(msg)
print(data)
if data["method"] == "rpcCommand":
rpc = data["params"]
method = rpc["method"]
params = rpc["params"]
if method == "move":
steps = int(params.get("steps", 200))
direction = int(params.get("direction", 1))
speed = int(params.get("speed", 500))
print("Move:", steps, direction, speed)
DIR.value(direction)
for i in range(steps):
STEP.value(1)
time.sleep_us(speed)
STEP.value(0)
time.sleep_us(speed)
elif method == "cw":
DIR.value(1)
for i in range(200):
STEP.value(1)
time.sleep_us(500)
STEP.value(0)
time.sleep_us(500)
elif method == "ccw":
DIR.value(0)
for i in range(200):
STEP.value(1)
time.sleep_us(500)
STEP.value(0)
time.sleep_us(500)
except Exception as e:
print("ERROR:", e)
# =====================
# MQTT
# =====================
client = MQTTClient(
"esp32-stepper",
THINGSBOARD_HOST,
user=ACCESS_TOKEN,
password=""
)
client.set_callback(rpc_callback)
print("Connecting ThingsBoard...")
client.connect()
print("Connected")
client.subscribe(
b"v1/devices/me/rpc/request/+"
)
print("Subscribed")
# =====================
# MAIN LOOP
# =====================
while True:
try:
client.check_msg()
time.sleep_ms(100)
except Exception as e:
print("MQTT Error:", e)
time.sleep(5)