Controlling the position of a servo is very similar to controlling the intensity of a LED.The circuit is therefore very similar to the one used in project 004. Just like in that project the total resistance of the potentiometer is not important as long as it is somewhere between 1 KΩ and 100 KΩ.

The circuit

For this project you need to build the following circuit.

Arduino-project 005 – Servo


A servo expects a pulse-width-modulated (PWM) signal just like the one we used to contorl the LED in project 002 och 004, but the servo has a little higher requirements and to solve this there are ready-made code available so we don’t have to do this ourselves every time we want to control a servo. The first thing we do in our code is to include this ready-made code and then create an object representing the servo. An object in programming context is basically a variable that has different functions connected to it for doing various operations on the data that the variable contains. In this example we use the function attach() to tell the object which output the servot is connected to and write() to set the position of the servo. The position is given as an angle between 0 and 180 degrees. This means that we need to scale the value read from the potentiometer, just like in project 004.


// Include the code library for controlling servos.
#include <Servo.h>

// Create a servo-object for controlling the servo motor.
Servo my_servo;

// Reserve memory for variables to store data in.
int value_in;
int angle;

void setup() {
  // Tell the servo object which output the servo is connected to.
  // Set pin A0 to be an input.
  pinMode(A0, INPUT);

void loop() {
  // Read the position of the potentiometer. This gives a value between 0 and 1023.
  value_in = analogRead(A0);
  // Scale the value so that it lies between 0 and 180.
  angle = map(value_in, 0, 1023, 0, 180);
  // Set the position of the servo.
  // Wait a bit for the servo to move to the corrected position.

Pin It on Pinterest

Share This