SG90 Servo Motor Control
The SG90 is a popular hobby servo that can position its output shaft to a specific angle (0–180°) using PWM signals.
Key idea:
Servos expect a 50 Hz PWM signal (20ms period) with pulse widths of 1000–2000 µs. The Arduino Servo library handles this automatically.
Wiring
SG90 Red (VCC) ────── 5V (or external 5V supply)
SG90 Brown (GND) ──── GND
SG90 Orange (Signal) ─ Arduino Pin 9
Basic Servo Control
#include <Servo.h>
Servo myServo;
void setup() {
myServo.attach(9); // Attach servo to pin 9
}
void loop() {
myServo.write(0); // Move to 0°
delay(1000);
myServo.write(90); // Move to 90°
delay(1000);
myServo.write(180); // Move to 180°
delay(1000);
}Smooth Sweeping
#include <Servo.h>
Servo myServo;
int pos = 0;
void setup() {
myServo.attach(9);
}
void loop() {
// Sweep from 0° to 180°
for (pos = 0; pos <= 180; pos += 1) {
myServo.write(pos);
delay(15);
}
// Sweep back from 180° to 0°
for (pos = 180; pos >= 0; pos -= 1) {
myServo.write(pos);
delay(15);
}
}Servo Specifications (SG90)
| Parameter | Value |
|---|---|
| Operating voltage | 4.8–6V |
| Stall torque | 1.8 kg/cm (at 4.8V) |
| Operating speed | 0.12 sec/60° (at 4.8V) |
| Weight | 9g |
| Pulse width | 1000–2000 µs |
| PWM frequency | 50 Hz |
Multiple Servos
#include <Servo.h>
Servo servo1;
Servo servo2;
void setup() {
servo1.attach(9);
servo2.attach(10);
}
void loop() {
servo1.write(0);
servo2.write(180);
delay(1000);
servo1.write(90);
servo2.write(90);
delay(1000);
servo1.write(180);
servo2.write(0);
delay(1000);
}Key Takeaways
- Servos use PWM: 50 Hz, 1000–2000 µs pulse width for 0–180°
- Arduino Servo library handles PWM generation automatically
- Use
servo.attach(pin)andservo.write(angle) - Always power servos from an external supply, not Arduino 5V pin
- Servo library conflicts with PWM on pins 9/10 on Arduino Uno
Resources
- Arduino Servo Library: https://www.arduino.cc/reference/en/language/functions/servo/
- Video: Servo Motor Control - https://www.youtube.com/watch?v=9VZty4UjQZk
- SG90 Datasheet: https://www.futaba-rc.com/servos/sg90/