Control Servo Motor with Arduino Tutorial

In this article, we will control servo motor angle using Potentiometer with Arduino UNO.

Servo motors have a built in feedback circuitry which helps to find the position of servo axis, this gives accurate movements of the axis.Servos can be used to control movements of robots like arms, legs or to rotate objects e.g Spider Bot where Arduino control servo motor for the leg movements of a spider.Servo motor requires PWM signal i.e Pulse width Modulation Signal for controlling the position of the shaft so we need to use one of the PWM pins of the Arduino.PWM pins are marked by a ‘~’ character.Here we are going to use the D9 pin of Arduino UNO.So let’s start.

Things You Need

Servo Motor

Wiring Servo with Arduino

D9 << Servo Signal Pin (Yellow/White wire)
5V << Servo Power (Red wire)
GND << Servo Ground (Brown/Black wire)
A0 << Potentiometer Output

Code to control servo motor
In the first, we include the Servo Library to control servo.Then we create an Object named servo_control, initialize angle variable with 0 and declare Potentiometer Output Pin A0.In the setup function, we specify the servo signal pin i.e 9 in our case.

Inside the Loop Function, we read the analog value of the Potentiometer and map it to 0-179 (i.e 180 values corresponding to 180 degrees).The mapped values are then used to turn the servo motor.Therefore as we turn the Potentiometer Knob, the shaft of the servo motor Turns.

#include //Servo library

Servo servo_control; //initialize a servo object for the connected servo

int angle = 0;
int potentiometer = A0; // initialize the A0analog pin for potentiometer

void setup()
servo_control.attach(9); // attach the signal pin of servo to pin9 of arduino

void loop()
angle = analogRead(potentiometer); // reading the potentiometer value between 0 and 1023
angle = map(angle, 0, 1023, 0, 179); // scaling the potentiometer value to angle value for servo between 0 and 180)
servo_control.write(angle); //command to rotate the servo to the specified angle