Servo sweep — Arduino code
A servo moves to an angle you choose and holds it there. Two sketches cover almost everything: one that jumps to set angles, and one that sweeps smoothly from 0° to 180°.
What you need
- • Arduino Uno
- • 1 × SG90 micro servo
- • 3 jumper wires
Wiring
- 1Brown or black servo wire to GND.
- 2Red servo wire to 5 V (use a separate battery pack for bigger servos).
- 3Orange or yellow signal wire to digital pin 9.
The code
servo-motor.ino
#include <Servo.h>
Servo arm;
void setup() {
arm.attach(9); // signal wire on pin 9
}
void loop() {
for (int angle = 0; angle <= 180; angle++) {
arm.write(angle);
delay(15);
}
for (int angle = 180; angle >= 0; angle--) {
arm.write(angle);
delay(15);
}
}Line by line
- #include <Servo.h>
- Loads the built-in Servo library — no download needed.
- Servo arm;
- Creates a servo object you can command by name.
- arm.attach(9);
- Connects that object to the signal pin.
- arm.write(angle);
- Moves the horn to that angle in degrees, 0 to 180.
- delay(15);
- Gives the servo time to reach each step, which makes the sweep smooth.
When it does not work
- My servo jitters or resets the board
- It is drawing more current than the USB port can supply. Power the servo from a 4×AA battery pack and join its ground to the Arduino GND.
- How do I hold one exact angle?
- Delete the loops and call arm.write(90); once inside setup() — the servo will move there and stay.
- Which pins work for servos?
- Any digital pin works with the Servo library, but pins 9 and 10 are the usual choice on an Uno.
Want the theory behind it?