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
- Arduino IDE (download link: https://www.arduino.cc/en/software)
- 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.
Other Preparation Work
- Follow the Arduino Environment Configuration steps to set up the board and port
- Ensure the Servo power port is properly connected for high-current servos (avoid using Type-C for high-voltage peripherals)
- 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
#define PWM_PIN 6
#define PWM_FREQ 50
#define PWM_RES 10
// Servo angle → Duty cycle value (10-bit resolution)
int angleToDuty(float angle) {
// Fine-tune these boundary values based on the specific servo
const int DUTY_0DEG = 26; // Duty cycle value for 0°
const int DUTY_180DEG = 128; // Duty cycle value for 180°
return map(angle, 0, 180, DUTY_0DEG, DUTY_180DEG);
}
void setup() {
ledcAttach(PWM_PIN, PWM_FREQ, PWM_RES);
}
void loop() {
ledcWrite(PWM_PIN, angleToDuty(0)); // Move to 0°
delay(1000);
ledcWrite(PWM_PIN, angleToDuty(180)); // Move to 180°
delay(1000);
}
Result
Burn the sample program to cyclically rotate Servo 1 in the range of 0-180°.
Was this article helpful?
