Precision Servo Motor Angle Control via PWM
Generate Pulse Width Modulation (PWM) signals to position a servo motor shaft precisely from 0° to 180°.
Robotic arm joints, camera pan-tilt stabilizers, RC aircraft rudders, and automated gate barriers.
A servo motor houses a DC motor, reduction gear train, potentiometer feedback, and control IC. A periodic 50Hz PWM signal (20ms frame) where pulse width varies between 1.0ms (0°) and 2.0ms (180°) dictates the target angular position.
Pin Connection & Wiring Table
| Component Pin / Terminal | Microcontroller Pin (ESP32 / Arduino) | Wiring Note |
|---|---|---|
| Brown / Black Wire (GND) | GND | Common ground |
| Red Wire (VCC) | 5V / VIN | Motor power |
| Orange / Yellow Wire (PWM Signal) | GPIO 13 / Pin 9 | Control signal line |
Step-by-Step Plug & Play Assembly
Connect the brown wire to ground and the red wire to 5V.
Connect the orange control signal wire to GPIO 13.
Mount a horn indicator on the motor splines so you can visibly track the rotation angles.
Complete Tested Source Code
// NovaCircuit Project 5: Servo Motor Angle Sweeper
#include <ESP32Servo.h> // Or <Servo.h> for Arduino Uno
Servo myServo;
const int SERVO_PIN = 13;
void setup() {
Serial.begin(115200);
myServo.attach(SERVO_PIN);
Serial.println("Servo Motor Sweeper Activated");
}
void loop() {
// Sweep from 0 to 180 degrees
for (int pos = 0; pos <= 180; pos += 15) {
myServo.write(pos);
Serial.print("Angle: ");
Serial.println(pos);
delay(100);
}
delay(500);
// Sweep back from 180 to 0 degrees
for (int pos = 180; pos >= 0; pos -= 15) {
myServo.write(pos);
Serial.print("Angle: ");
Serial.println(pos);
delay(100);
}
delay(500);
}myServo.attach(pin) allocates a hardware PWM timer. myServo.write(angle) converts the degree parameter (0-180) into the exact microsecond duty pulse needed by the servo potentiometer control loop.
Expected Physical Output
- •Servo jittering or resetting MCU: Servos draw peak current when starting; power from a dedicated 5V power supply or external battery if microcontroller brown-outs occur.
- •Never force the servo horn by hand beyond its mechanical stops.
- •Keep fingers away from moving horn arms and do not stall the motor.
Related Book Chapter & Hardware Kit
Covered in depth within Chapter 8: Introduction to ESP32. Build this easily with the Sensor Explorer Kit.