Control 2 Servos with Arduino

Updated: Apr 16

Learn how to control 2 servo motors with potentiometers and an Arduino UNO

[Disclaimer: As an Amazon Associate I earn from qualifying purchases from paid links in this article]

Introduction

It's important to be able to control servo motor actuators from an analog signal. In this post we will be directly controlling the rotation angle of each servo from potentiometers we can turn with our hand (kind of like an excavator). Once the basics are understood, this knowledge can be modularized and then used in more interesting projects that require pan and tilt.


Parts List (contains paid links):

Arduino UNO (1): https://amzn.to/3mHeKnz

Potentiometer (2): https://amzn.to/3a6Bvw7

Jumper Wires (Assorted): https://amzn.to/3wUxtjW

Pan and Tilt Set (1 set of 2): https://amzn.to/3uMZ5Wp

Servo Motor (2): https://amzn.to/3g4nyCA

Small screwdriver (1) https://amzn.to/3sjK50C


Hardware

Image of the completed project. If this were soldered into an actual enclosure than we wouldn't have wires all over the place.

Software

Each servo rotates a total of 180 degrees, which means that it takes a value as input from 0 to 180. So if we define our servo as 'myServo;, for example, we can use this to rotate it 90 degrees:

myServo.write(90);

But for this project we don't want to hardcode a numerical value such as what we have above with '90'. We are going to pass our value as a variable based off the reading from potentiometers. Our potentiometers range in analog value from 0 to 1023. So we have to map the analog value to relative value in degrees. So the question is, how many degrees to we want to move for every 1 unit of the potentiometer reading? Since we need to break 180 degrees into 1023 parts, we divide. 180 / 1023 = 0.17595.


This means that we multiply each analog reading by 0.17595 to scale it to the appropriate degrees.


In code, it would look like this:

servoInput1 = analogRead(analogInPinLeft);
float scaling = 180.0 / 1023.0;
myServo.write(servoInput1 * scaling)


Here is the full version of the final Arduino code:

#include <Servo.h>

const int analogInPinLeft = A0;  
const int analogInPinRight = A1;  
float servoInput1 = 0;     
float servoInput2 = 0;    

Servo myServo1; 
Servo myServo2;

int pos1 = 0;  
int pos2 = 0;
float scaling = 180.0 / 1023.0;

void setup() {     
   myServo1.attach(9);
   myServo2.attach(10);   
}

void loop() {
 servoInput1 = analogRead(analogInPinLeft);
 servoInput2 = analogRead(analogInPinRight); 
 int move1 = int(servoInput1 * scaling);
 int move2 = int(servoInput2 * scaling); 
 myServo1.write(move1);
 myServo2.write(move2);
}