Example Code for Arduino-PWM-driven DC Motors

This project demonstrates how to use PWM signals to control the direction and speed of DC motors connected to the Romeo Mini. By adjusting PWM values and direction pins, users can learn the basics of motor control, PWM application, and proper wiring for motor drivers.

Hardware Preparation

  • DC Motors: x2
  • Romeo Mini: x1

Software Preparation

  1. Arduino IDE (download link: https://www.arduino.cc/en/software)
  2. ESP32 board support package (version 2.0.0) installed via Arduino Boards Manager (follow the [Arduino Environment Configuration] steps)

Wiring Diagram

The module is powered by 5-12V. Choose an appropriate power supply voltage based on the motors.

Motor Connection Diagram

Other Preparation Work

  1. Add the ESP32 board URL to Arduino IDE: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
  2. Install the ESP32 board support package (version 2.0.0) via Tools -> Board -> Boards Manager
  3. Select "ESP32C3 Dev Module" from Tools -> Board
  4. Configure USB CDC to "Enable" for serial monitor use
  5. Select the correct serial port (press and hold BOOT + RST if the port is not recognized)
EN PH Function
H H Forward
H L Reverse
PWM L Forward
PWM H Reverse

Sample Code

int EN1 = 0; // PWM control for motor M1
int PH1 = 1; // Direction control for motor M1
int EN2 = 2; // PWM control for motor M2
int PH2 = 10; // Direction control for motor M2

void setup() {
  pinMode(EN1, OUTPUT);
  pinMode(PH1, OUTPUT);
  pinMode(EN2, OUTPUT);
  pinMode(PH2, OUTPUT);
}

void loop() {
  M1_Forward(200); // Motor M1 moves forward with adjustable PWM
  M2_Forward(200); // Motor M2 moves forward with adjustable PWM
  delay(5000);
  M1_Backward(200); // Motor M1 moves backward with adjustable PWM
  M2_Backward(200); // Motor M2 moves backward with adjustable PWM
  delay(5000);
}

void M1_Forward(int Speed1) // Forward fast decay mode for M1 motor, larger Speed1 value results in faster motor rotation
{
  analogWrite(EN1, Speed1);
  digitalWrite(PH1, LOW);
}

void M1_Backward

Result

Execute the sample program by commanding simultaneous rapid forward rotation of motors M1 and M2, followed by simultaneous slow reverse rotation of motors M1 and M2.

Was this article helpful?

TOP