Introduction
Servo motors are essential in robotics — they allow precise angular positioning. In this tutorial, you'll learn to control a standard servo using Arduino.
Components Required
- Arduino Uno
- SG90 Micro Servo Motor
- 10kΩ Potentiometer (for Part 2)
- Breadboard and jumper wires
Wiring
| Servo Wire | Arduino |
|---|---|
| Red (VCC) | 5V |
| Brown (GND) | GND |
| Orange (Signal) | Pin 9 |
Part 1: Basic Sweep
#include <Servo.h>
Servo myServo;
void setup() {
myServo.attach(9);
}
void loop() {
for (int pos = 0; pos <= 180; pos++) {
myServo.write(pos);
delay(15);
}
for (int pos = 180; pos >= 0; pos--) {
myServo.write(pos);
delay(15);
}
}This sweeps the servo from 0° to 180° and back, continuously.
Part 2: Potentiometer Control
Add a potentiometer — connect its middle pin to A0, and the outer pins to 5V and GND.
#include <Servo.h>
Servo myServo;
void setup() {
myServo.attach(9);
}
void loop() {
int val = analogRead(A0);
int angle = map(val, 0, 1023, 0, 180);
myServo.write(angle);
delay(15);
}Now turning the potentiometer knob directly controls the servo position!
Tips
- Never power multiple servos directly from Arduino — use an external 5V supply
- The
Servolibrary disables PWM on pins 9 and 10 - For continuous rotation servos,
write(90)= stop,write(0)= full speed one direction,write(180)= full speed other direction