Chapter 9 · Arduino Practicals and Programming Projects

Practical 3Connecting a Servo Motor with Arduino UNO R3

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 wireArduino
Brown / black (GND)GND
Red (power)5V
Orange / yellow (signal)Pin 9
Arduino UNOPin 95VA0GNDSG90servoorange: signalred: 5V brown: GND10 kΩ potentiometer(Part B; wiper to A0)
Practical 3 circuit

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.

Viva questions

  1. What is the difference between a DC motor and a servo?
  2. Which Arduino function sets the servo angle?
  3. Why is delay(15) used in the loop?
Show viva answers
  1. A servo has feedback and a controller, so it goes to and holds a commanded angle; a DC motor just spins.
  2. write(angle).
  3. To give the servo time to reach each new position and to make the sweep smooth.