Slide potentiometer controls a servo
Move a slider and a servo follows it: map an analog reading to an angle.
Input · Beginner
In a real product: Radio-controlled model (Consumer electronics): A slider sets a servo's position.
A slide potentiometer works like a rotary one, but in a straight line. Here its position sets a servo's angle, so the servo arm copies the slider: the idea behind remote-control steering.
What you'll learn
- Driving a hobby servo with the Servo library
- Mapping 0–1023 to 0–180 degrees with
map() - Powering a servo: signal, + and − wires
How it works
The slider's SIG pin goes to A0, with VCC on 5V and GND on GND, so analogRead(A0) gives 0 to 1023 along its travel.
A servo turns to an angle set by the width of a pulse sent 50 times a second: about 0.5 ms for 0°, 2.4 ms for 180°. The Servo library makes those pulses on pin 9. servo.write(angle) sets the angle, and map() turns the reading into 0–180.
Try this
- Drag the slider while it runs and watch the arm follow.
- Smooth the motion: move the servo at most 2° per loop toward the target.
- Use two sliders and two servos to make a pan-tilt mount.
sketch.ino
// A slide potentiometer on A0 sets the angle of a servo on pin 9.
#include <Servo.h>
Servo servo;
void setup() {
servo.attach(9);
}
void loop() {
int reading = analogRead(A0); // 0..1023 along the slider
int angle = map(reading, 0, 1023, 0, 180); // 0..180 degrees
servo.write(angle);
delay(15);
}