Servo Sweep
Servo motor sweeping back and forth 0 to 180 degrees.
- Beginner
- Motors
- 2 parts
Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.
How it works
A servo is a small motor that turns to a position you command, from 0 to 180 degrees. It has three wires: power (5V), ground, and a signal wire that carries the position command. Here the signal wire is on pin 9.
The sketch uses the Servo library: myservo.attach(9) ties the servo to pin 9, and myservo.write(pos) turns it to an angle. loop() steps the angle up from 0 to 180 one degree at a time, pausing 15 milliseconds between steps, then steps it back down to 0. The upward sweep also prints each angle to the Serial tab.
Parts
- Arduino Uno
- Servo Motor
Wiring
- Arduino Uno D9 → Servo Motor SIG
- Arduino Uno 5V → Servo Motor VCC (5V)
- Arduino Uno GND → Servo Motor GND
Arduino code
// Servo Sweep
#include <Servo.h>
Servo myservo;
int pos = 0;
void setup() {
myservo.attach(9);
Serial.begin(9600);
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) {
myservo.write(pos);
Serial.print("Angle: ");
Serial.println(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(15);
}
}
Try changing it
- Sweep faster by changing delay(15) to delay(5) in both loops.
- Limit the sweep to a quarter turn: change 180 to 90 in both for loops.