A servo motor controller with auto-sweep, potentiometer manual control, and serial command input — the foundation of robotic arms, camera gimbals, and RC vehicles.
The Servo library is built into the Arduino IDE — no installation needed.
#include <Servo.h>
Servo myServo;
const int SERVO_PIN = 9;
void setup() {
myServo.attach(SERVO_PIN);
Serial.begin(9600);
}
void loop() {
// Sweep forward
for (int angle = 0; angle <= 180; angle += 5) {
myServo.write(angle);
Serial.println(angle);
delay(30);
}
// Sweep back
for (int angle = 180; angle >= 0; angle -= 5) {
myServo.write(angle);
Serial.println(angle);
delay(30);
}
}
Map the potentiometer reading (0-1023) to servo angle (0-180) using map().
#include <Servo.h>
Servo myServo;
const int SERVO_PIN = 9;
const int POT_PIN = A0;
void setup() {
myServo.attach(SERVO_PIN);
Serial.begin(9600);
}
void loop() {
int rawValue = analogRead(POT_PIN); // 0 to 1023
int angle = map(rawValue, 0, 1023, 0, 180); // scale to 0-180
myServo.write(angle);
Serial.print("Pot: "); Serial.print(rawValue);
Serial.print(" Angle: "); Serial.println(angle);
delay(20);
}
Send angle commands from the Serial Monitor to position the servo precisely.
#include <Servo.h>
Servo myServo;
const int SERVO_PIN = 9;
int currentAngle = 90;
void setup() {
myServo.attach(SERVO_PIN);
myServo.write(90); // Start at centre
Serial.begin(9600);
Serial.println("Servo Controller Ready");
Serial.println("Send an angle (0-180) to position the servo.");
}
void loop() {
if (Serial.available() > 0) {
int angle = Serial.parseInt();
if (angle >= 0 && angle <= 180) {
// Smooth movement: step toward target
int step = (angle > currentAngle) ? 1 : -1;
while (currentAngle != angle) {
currentAngle += step;
myServo.write(currentAngle);
delay(10); // 10ms per degree = smooth sweep
}
Serial.print("Moved to: "); Serial.print(angle); Serial.println(" degrees");
} else {
Serial.println("Error: angle must be 0-180");
}
}
}
You can now position any servo precisely from 0 to 180 degrees. Two servos and a camera mount = a pan-tilt gimbal. Three servos = a robotic arm base. Six servos = a hexapod walker. Servos are the muscles of the robot world.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.