Servo Example

Servo

In this example we'll show you how to control the position of a RC servo motor with your Arduino and a potentiometer. 
The sketch need the Servo library, which provides functions to fully control servos.

Hardware

  • Arduino Board
  • 1 x Servo Motor
  • 1 x Potentiometer
  • a bunch of wires

Circuit

Servo example circuit 
Servo motors have three wires: power, ground, and signal. 
The power wire usually coloured red, and it needs to be connected to the 5V pin on the Arduino board. 
The ground wire is usually coloured black or brown and it needs to be connected to a ground pin on the Arduino board. 
The signal pin is usually coloured yellow or orange and it needs to be connected to pin 9 (or any other PWM pin) on the Arduino board.

The potentiometer should be wired so that its two outer pins are connected to power (+5V) and ground, and its middle pin is connected to analog input 0 on the Arduino.

Schematic

Servo example schematic

Code

 
 
// include the library that allows you to control the servo
#include <Servo.h>
 
Servo myservo; // create servo object
 
int potentiometerPin = 0; // analog pin used for the potentiometer
int val;// variable to read the value from the analog pin
 
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
 
void loop() {
// reads the value of the potentiometer (val will be a value between 0 and 1023)
val = analogRead(potentiometerPin);
 
// scale the value in order to control the servo
// (servo uses values between 0 and 180)
val = map(val, 0, 1023, 0, 180);
 
// sets the servo position according to the scaled value
myservo.write(val);
 
// waits for the servo to get there
delay(15);
}