Arduino Example Code – Motor Forward/Reverse & Stop
Based on FireBeetle 2 ESP32-E, PWM signals are used to drive the N20 geared motor to realize forward rotation, reverse rotation and stop control of the motor. Operation status information is output via serial port.
Hardware Preparation
Software Preparation
- Download and install Arduino IDE: Download Arduino IDE
- Download and install the DFRobot_N20Motor library: Download DFRobot_N20Motor 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: PA | Connect to | Main Controller Pin: 12 |
| Motor Pin: PB | Connect to | Main Controller Pin: 4 |
Sample Code
#include "DFRobot_N20Motor.h"
// ESP32‑E pin definition
#define N20_INA_PWM_PIN 12
#define N20_INB_PWM_PIN 4
/**
* Note:
* - The N20 motor requires PWM signal to control its speed.
* - The PWM signal must be output from the main controller's PWM pins, ordinary digital pins cannot be used for direct driving.
*/
DFRobot_N20Motor motor(N20_INA_PWM_PIN, N20_INB_PWM_PIN);
void setup()
{
Serial.begin(115200);
delay(100);
Serial.println();
Serial.println("========================================");
Serial.println(" DFRobot N20 Motor");
Serial.println(" Motor Control Example");
Serial.println("========================================");
if (!motor.begin()) {
Serial.println("[ERROR] Motor initialization failed, please check pin configuration.");
while (1) {
delay(100);
}
}
Serial.print("[OK] Motor initialized (INA PWM pin: ");
Serial.print(N20_INA_PWM_PIN);
Serial.print(", INB PWM pin: ");
Serial.print(N20_INB_PWM_PIN);
Serial.println(")");
Serial.println("Start speed control loop...");
Serial.println();
}
void loop()
{
Serial.println("-> Speed 200");
motor.setSpeed(200);
delay(2000);
Serial.println("-> Speed 0");
motor.setSpeed(0);
delay(2000);
Serial.println("-> Speed -200");
motor.setSpeed(-200);
delay(2000);
Serial.println("-> Speed 0");
motor.setSpeed(0);
delay(2000);
Serial.println();
}
Result
Upload the code and open the Serial Monitor (Baud rate: 115200). After successful initialization, the motor automatically cycles through the sequence: forward rotation for 2s → stop for 2s → reverse rotation for 2s → stop for 2s. The serial port prints the current speed status in real time. See the figure below for output results.

Was this article helpful?
