Remote Actuator Control ======================= This example demonstrates how to make mPython IoT subscribe to an MQTT topic and remotely control actuators (such as LEDs, servos, water pumps, etc.) connected via the HY2.0-4PIN interface based on received messages, enabling IoT remote control. Basic Principle --------------- mPython IoT acts as an MQTT subscriber, continuously listening to a specified topic. When an IoT platform or other device publishes a control command to that topic, mPython IoT parses the message via a callback function and drives the corresponding actuator. Remote LED Control ------------------ The following example subscribes to a topic and controls an LED on/off based on received ``on`` / ``off`` messages:: from umqtt.simple import MQTTClient import network from machine import Pin import time # Connect to Wi-Fi sta = network.WLAN(network.STA_IF) sta.active(True) sta.connect('your_ssid', 'your_password') while not sta.isconnected(): time.sleep(0.5) # MQTT configuration SERVER = "192.168.1.100" PORT = 1883 CLIENT_ID = "mpython_iot_001" TOPIC = "classroom/led" # LED connected to GPIO pin led = Pin(0, Pin.OUT) def sub_cb(topic, msg): print("Received topic: %s, message: %s" % (topic.decode(), msg.decode())) if msg == b"on": led.value(1) # Turn on LED print("LED turned on") elif msg == b"off": led.value(0) # Turn off LED print("LED turned off") client = MQTTClient(CLIENT_ID, SERVER, PORT, keepalive=30) client.connect() client.set_callback(sub_cb) # Set callback function client.subscribe(TOPIC) # Subscribe to topic print("Subscribed to topic: %s" % TOPIC) while True: client.wait_msg() # Loop waiting for messages .. Note:: The ``topic`` and ``msg`` received by the callback function are both byte types. When comparing, use byte literals like ``b"on"``, or convert to string with ``.decode()`` before comparing. Remote Servo Control -------------------- Replace the actuator with a servo to control it to different angles based on messages:: from machine import Pin, PWM servo = PWM(Pin(1), freq=50) # Servo signal wire connected to GPIO1 def set_angle(angle): # Map 0~180 degrees to servo duty cycle duty = int(angle / 180 * 100 + 2.5) servo.duty(duty) def sub_cb(topic, msg): cmd = msg.decode() if cmd == "open": set_angle(90) # Rotate to 90 degrees elif cmd == "close": set_angle(0) # Rotate to 0 degrees .. Hint:: Similarly, the actuator can be replaced with a water pump, relay, buzzer, or other mPython Module actuators by simply modifying the control logic in the callback function. For actuator wiring instructions, see :doc:`mPython Module Actuator Documentation ` . Related Documentation --------------------- - :doc:`3_2_mqtt` - :doc:`3_4_upload` - :doc:`3_6_link_ledong`