Arduino Example Code – Motor Forward/Reverse & Stop
Based on FireBeetle 2 ESP32-E, hardware UART is used to send Modbus commands to drive the N20 UART geared motor, enabling motor forward rotation, reverse rotation and stop control, with runtime status logs printed via serial port.
Hardware Preparation
Software Preparation
- Download and install Arduino IDE: Download Arduino IDE
- Download and install the DFRobot_N20SerialMotor library: Download DFRobot_N20SerialMotor library
- Download and install the DFRobot_RTU library: Download DFRobot_RTU Library
- Library Installation Guide: View Installation Guide
Wiring Diagram

Connection Description:
| Motor Pin: + | Connect to | Main Controller Pin: VCC |
|---|---|---|
| Motor Pin: - | Connect to | Main Controller Pin: GND |
| Motor Pin: R | Connect to | Main Controller Pin: 26/TX |
| Motor Pin: T | Connect to | Main Controller Pin: 25/RX |
Sample Code
#include "DFRobot_N20SerialMotor.h"
/*
* ESP32‑E Wiring:
* N20 motor module VCC → 5V
* N20 motor module GND → GND
* N20 motor module RX → ESP32 GPIO25 (Serial1‑TX)
* N20 motor module TX → ESP32 GPIO26 (Serial1‑RX)
*/
#define MOTOR_ADDR 1
#define MOTOR_BAUD 9600
// Use ESP32 hardware Serial1
DFRobot_N20SerialMotor motor(MOTOR_ADDR, &Serial1);
void setup()
{
Serial.begin(115200);
// Serial1: Baud rate 9600, 8N1, TX=25, RX=26
Serial1.begin(MOTOR_BAUD, SERIAL_8N1, 25, 26);
delay(1000);
Serial.println();
Serial.println(F("========================================"));
Serial.println(F(" DFRobot N20 Serial Motor"));
Serial.println(F(" ESP32‑E Single Motor Control"));
Serial.println(F("========================================"));
// Motor initialization, retry loop on failure
while (motor.begin() != 0) {
Serial.println(F("[ERROR] Motor init failed, retrying..."));
delay(1000);
}
Serial.print(F("[OK] Motor initialized (Modbus addr: "));
Serial.print(MOTOR_ADDR);
Serial.println(F(")"));
Serial.println(F("Starting speed control loop..."));
Serial.println();
}
void loop()
{
Serial.println(F("-> Speed 200"));
motor.setSpeed(200);
delay(2000);
Serial.println(F("-> Stop"));
motor.setSpeed(0);
delay(2000);
Serial.println(F("-> Speed -200"));
motor.setSpeed(-200);
delay(2000);
Serial.println(F("-> Stop"));
motor.setSpeed(0);
delay(2000);
Serial.println();
}
Result
Compile and upload the code, then open the Serial Monitor (Baud rate: 115200). After successful communication initialization, the motor cycles through forward rotation for 2s, stop for 2s, reverse rotation for 2s, stop for 2s. Control logs are printed simultaneously via serial port, as shown in the figure below.

Was this article helpful?
