Aim. To control the angle of a servo motor from an Arduino.
Components. Arduino UNO R3, SG90 (or similar) servo, 10 kΩ potentiometer (for part B), jumper wires.
Concepts used. PWM control signal, the Servo library, analog input and map().
Wiring.
| Servo wire | Arduino |
|---|---|
| Brown / black (GND) | GND |
| Red (power) | 5V |
| Orange / yellow (signal) | Pin 9 |
Part A: Sweep
Arduino C/C++
#include <Servo.h>
Servo myServo;
void setup() {
myServo.attach(9);
}
void loop() {
for (int angle = 0; angle <= 180; angle++) { // sweep one way
myServo.write(angle);
delay(15); // time for the servo to move
}
for (int angle = 180; angle >= 0; angle--) { // sweep back
myServo.write(angle);
delay(15);
}
}Part B: Position controlled by a potentiometer. Connect the potentiometer's outer legs to 5V and GND and the middle leg to A0.
Arduino C/C++
#include <Servo.h>
Servo myServo;
void setup() {
myServo.attach(9);
}
void loop() {
int reading = analogRead(A0); // 0..1023
int angle = map(reading, 0, 1023, 0, 180); // 0..180
myServo.write(angle);
delay(15);
}Expected result. Part A: the servo arm sweeps smoothly between 0° and 180°. Part B: the arm follows the knob.
Troubleshooting.
- Servo jitters or the Arduino resets: the servo is drawing too much current; use a separate 5 to 6 V supply and join the grounds.
- Servo does not move: check the signal wire pin and the polarity of the supply wires.
- Servo buzzes at the limits: reduce the angle range, for example 10 to 170.
Viva questions
- What is the difference between a DC motor and a servo?
- Which Arduino function sets the servo angle?
- Why is
delay(15)used in the loop?
Show viva answers
- A servo has feedback and a controller, so it goes to and holds a commanded angle; a DC motor just spins.
write(angle).- To give the servo time to reach each new position and to make the sweep smooth.