Servo Potentiometer Control
Control a servo's position with a potentiometer knob.
- Intermediate
- Motors
- 3 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
Two parts talk to the Arduino here. The potentiometer’s wiper feeds analog pin A0, and a servo’s signal wire is on pin 9. Turning the knob changes the number the Arduino reads, and the sketch turns that number into a servo angle.
Every 20 milliseconds, loop() reads A0 (0 to 1023), uses map() to rescale it to 0 to 180 degrees, and tells the servo to move there. The knob is in effect a remote control for the servo: drag the potentiometer in the editor and watch the arm follow. The angle is printed to the Serial tab.
Parts
- Arduino Uno
- Potentiometer
- Servo Motor
Wiring
- Arduino Uno 5V → Potentiometer VCC
- Potentiometer Wiper → Arduino Uno A0
- Arduino Uno GND → Potentiometer GND
- Arduino Uno D9 → Servo Motor SIG
- Arduino Uno 5V → Servo Motor VCC (5V)
- Arduino Uno GND → Servo Motor GND
Arduino code
// Servo Potentiometer Control
#include <Servo.h>
Servo myservo;
void setup() {
myservo.attach(9);
Serial.begin(9600);
}
void loop() {
int val = analogRead(A0);
int angle = map(val, 0, 1023, 0, 180);
myservo.write(angle);
Serial.print("Angle: ");
Serial.println(angle);
delay(20);
}
Try changing it
- Keep the servo away from its end stops: change map(val, 0, 1023, 0, 180) to map(val, 0, 1023, 45, 135).
- Reverse the direction by swapping the last two numbers: map(val, 0, 1023, 180, 0).