Example Code for Arduino-PWM-Driven Servo Motor

This project shows how to use PWM to control a servo motor's rotation angle with the Romeo Mini. Users can learn servo control basics, PWM frequency configuration, and wiring for high-current peripherals.

Hardware Preparation

  • 5V PWM servo motor: x1
  • 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

Wiring Diagram

If you need to operate a servo motor or peripheral device with a voltage higher than 5V, connect the Servo terminal to the power supply. The power supply range should be between 5-12V. The VCC terminal voltage is equal to the input voltage at the Servo terminal. When the Servo terminal is not connected, the default VCC terminal voltage is 5V.

Motor Connection Diagram

Other Preparation Work

  1. Follow the Arduino Environment Configuration steps to set up the board and port
  2. Ensure the Servo power port is properly connected for high-current servos (avoid using Type-C for high-voltage peripherals)
  3. The servo's VCC voltage matches the Servo port input (5-12V) when connected; default is 5V if the Servo port is unpowered.

Sample Code

void setup() {
ledcSetup(0, 5000, 10); // Configure channel 0 with a frequency of 5KHz and 10-bit resolution
ledcAttachPin(6, 0); // Assign pin 6 as the output pin for channel 0
}

void loop() {
ledcWrite(0, 125); // Set the output of channel 0 to 125, producing a PWM output of 0 to 100% (0 to 1024)
delay(1000);
ledcWrite(0, 25);
delay(1000);
}

Result

Burn the sample program to cyclically rotate Servo 1 in the range of 0-180°.

Was this article helpful?

TOP