How to Control Servo Motors with Arduino & Code
How to Control Servo Motors with Arduino & Code
Welcome to our exciting exploration of controlling servo motors with Arduino and code! As we delve into this fascinating topic,
we’ll unlock an essential skill set in the world of robotics, animatronics, and motorized props. Servo motors, with their ability to
rotate with precision, form the backbone of various applications ranging from the nimble arms of robots to the expressive faces of
animatronic creatures, and even the intricate movements of motorized props in movies or stage performances. By mastering the
art of maneuvering these servos using an Arduino and some clever coding, you’ll have the power to breathe life into static objects,
creating dynamic, interactive projects. Whether you’re a hobbyist looking to enhance your home creations, an aspiring roboticist,
or a professional prop maker, understanding how to harness the versatility of servo motors is a game-changer. Let’s dive in and
start making things move!
Breadboard (optional)
Jumper wires (the male-to-male Dupont-style jumper wires will easily connect from the servo connector to Arduino pins)
The circuit diagram shows you where to connect each wire. Be sure you don’t have your Arduino microcontroller plugged in while
you make these connections.
1 Connect the Power: Connect the power wire of the servo to the 5V pin on the Arduino board, and the
servo’s ground wire to one of the GND pins on the Arduino.
2 Connect the Signal: Connect the signal wire to one of the digital pins on the Arduino. You can choose
any digital pin, but you’ll often see pin 9 used for servo motors.
Even with the SG90, I recommend only powering one of these servos directly from the Arduino. If you need to control more, then
you’ll need a separate power supply. On top of that, I usually only do this during the prototyping phase of a project. Once I have all
the components figured out, I like to move the servo to its own power source. Don’t forget that you may have other components
being controlled by the Arduino too like LEDs, sensors, etc that may run at the same time as the servo and all this draws current.
Servos can be powered separately either by batteries or a wall adapter. Just be sure that the power supply you choose matches
the voltage requirements of the servo and provides enough current for it to operate with the load it will be moving in your
animatronic, robot or motorized prop.
Here are examples of circuits using both a battery pack option and female DC jack adapter:
Common Ground
In electronics, “common ground” refers to a shared point of zero voltage. This serves as a common reference point for all
components in a circuit.
When you’re connecting a servo to an Arduino and using an external power supply, it’s crucial to establish a common ground. This
means that the ground of the Arduino (GND) and the ground of the external power supply should be connected together.
Voltage Reference: For signals to be accurately interpreted between different parts of a circuit, they need to share a
common voltage reference. This is especially important when you’re using an external power supply to power a servo and the
Arduino to control it.
Signal Integrity: Servo motors receive control signals from the Arduino through the signal wire. This signal is relative to the
ground of the Arduino. If the servo and the Arduino don’t share the same ground, the signal can become corrupted or not get
through at all, causing erratic behavior or even damage to the components.
Preventing Circuits Faults: A common ground helps to prevent potential difference from building up between different parts
of your circuit, which could lead to unpredictable behavior or even damage.
So when you’re connecting a servo motor to an Arduino AND using an external power supply, you must connect the ground of the
power supply (usually the black or negative wire) to the ground pin on the Arduino (GND). This ensures that they share a common
ground and that signals can pass between them correctly.
To include the library, go to Sketch => Include Library => Servo. As soon as you do this, you’ll notice a line of code appear at the very
top of your Arduino sketch:
#include <Servo.h>
Now that the servo library is included, we can start tapping into all the functionality it provides. But first, there’s a few more setup
items we have to cover.
Let’s say we’re building a robot arm, so I’ll call my servo object, armServo. Here’s how you would declare it:
#include <Servo.h>
Servo armServo;
Servo armServo;
void setup() {
armServo.attach(9);
}
If you break down this line of code, it starts with your servo’s name. In our case, it’s armServo. Then in the parenthesis, you put the
Arduino pin the servo is connected to. If you named your servo legServo and connected it to pin 5 on the Arduino, then that line of
code would look like: legServo.attach(5);
servoname.write(degrees);
#include <Servo.h>
Servo armServo;
void setup() {
armServo.attach(9);
}
void loop() {
armServo.write(180);
}
Try out different values from 0 to 180 in the parenthesis and watch your servo rotate as soon as you upload the code! This is a good
exercise to go through whenever you hook up a new servo. With the less expensive ones, you’ll quickly notice that they usually don’t
give you the full 0-to-180 range of motion. It will usually be more like 20 to 160.
#include <Servo.h>
Servo armServo;
void setup() {
armServo.attach(9);
armServo.write(0); //initial starting position
}
void loop() {
armServo.write(90); //rotate servo to 90 deg
delay(2000); //pause 2 secs
armServo.write(0);
This should look familiar to you because it’s the same line you used in the previous exercise. Because the setup() function runs first
and only one time, your servo will always reset to 0 degrees before moving on to the loop() function where the animation happens.
CONTINUOUS SWEEP
Sometimes you need your robot, motorized prop or animatronic to perform a repeating continuous movement. In our example, let’s
say we want our robot arm to wave continuously to people walking by. We can do this by having the servo motor sweep back and
forth from 0 to 180 degrees and then back to 0 degrees before starting the sweep again.
To accomplish this, we’ll use for loops to control the back and forth movements. For loops are great for handling repetitive actions
like incrementing or decreasing angles in a sequential manner. Let’s take a look at what the Arduino code to sweep a servo looks
like and then we’ll go over each line of code in detail.
#include <Servo.h>
Servo armServo;
void setup() {
armServo.attach(9);
}
void loop() {
As we scan down this code, much of it looks familiar. We start out by including the servo library and creating the servo object.
armServo.write(0);
In this example, I changed it up by doing it in the 3rd line of code above the setup() function like this:
int angle = 0;
I set up an integer variable (int) and named it angle. I then set the angle equal to 0. In Arduino code, a variable is a placeholder for a
value of a certain type that you can use and manipulate in your programs. The variable’s value can change during the execution of
the program—hence the term “variable”. In our case, the variable will represent an angle that will change as the servo horn sweeps
back and forth.
Both ways you’ve seen so far for establishing a starting position for your servo are correct but using a variable will allow us to
manipulate the angle in the loop() function. Any code that appears outside the loop() function runs only once so when we power up
our circuit the servo will reset to 0 degrees before starting the sweeping animation.
for Loops
In the loop() function of our sketch, we run into the first for loop which is a block of code that rotates our servo horn from 0
degrees to 180 degrees at an increment of 1 degree every 15 ms.
armServo.write(angle);
delay(15);
All for loops have the same basic structure as what you see above which is:
The for loop needs 3 pieces of information to work properly which are specified in the parenthesis separated by semi-colons(;).
The first is the “initial state”. In our case we set the value for the angle equal to 0:
angle = 0;
This code translates to “set the starting angle to 0”. The “initial state” portion of the for loop is only used one time, the very first
time the for loop is run. It then gets ignored because we’ll be rotating the servo position past this.
Second, we need to set up a “condition”. The for loop code block will run over and over again, executing the code within its curly
brackets {} so long as the condition we set up is true. If it becomes false then the program will jump out of the for loop code block
and continue going down executing the rest of the code.
Since we want the servo to go from 0 degrees to 180 degrees our condition looks like this:
This translates to “so long as the angle is less than or equal to 180” keep running this for loop.
The third piece of information is the “modifier”. In other words, how do you want to modify the angle every time the for loop is run?
In our case we want to increment the angle by 1 degree until we get to 180:
angle++
This code is short hand for angle + 1. So we want to add 1 to the current angle every time the for loop is run until the angle reaches
180 degrees.
After you specify the initial state, condition and modifier for the for loop in the parenthesis, you now have to tell it what code to
execute as long as the condition is met. In our case we want to rotate the servo to the angle calculated by the modifier:
armServo.write(angle);
delay(15);
Then the program will loop back to the beginning of the for loop for another round. Let’s say our servo’s angle is at 27 degrees. For
the next round, the for loop will check to see if 27 passes the condition. Since it is still less than 180 then it gets modified: 27 + 1 =
28. The servo will rotate to 28 degrees and hold it there for 15 ms before looping back to the beginning of the for loop again.
At some point the servo will reach 180 degrees and when it loops back to the beginning of the for loop, 181 will not meet the
condition so the program will jump out of that entire for loop code block and move on to the next line.
The next code block down the sketch is another for loop that takes the servo from 180 degrees back down to 0 degrees:
armServo.write(angle);
delay(15);
It uses the same structure as before, but now we’re counting down. Since the servo is at 180 from the previous for loop, we start
this one with an “initial state” of 180:
angle = 180;
Next, the condition is that as long as the angle is greater than or equal to 0, modify it:
angle >= 0;
Finally, in our modifier we want to subtract 1 degree each time the for loop is run:
angle–
So long as the condition we set in this second for loop is true, the code within the curly brackets {} will execute:
armServo.write(angle);
delay(15);
The servo will rotate from 180 degrees back down to 0 by 1 increment every 15 ms. Once the servo reaches 0 degrees and the for
loop tries to run again, the angle will be -1 which doesn’t meet the condition anymore. The program will jump out of this code block
and go back to the top of the main loop() function where it will encounter the first for loop again to repeat the sweep.
The servo will continue sweeping back and forth until you unplug it.
Affiliate Disclosure: Some links here might earn us enough nuts and bolts (aka commission) to keep the LEDs blinking and servos
turning. No extra cost to you, just a lil' fuel for our caffeine-powered nights of DIY-ing. We only endorse stuff that's survived our "Did-it-
Explode?" test. Build on, and thanks for the recharge!
JOIN NOW
STOP SCROLLING. START CREATING.
TAKE YOUR PROJECTS TO THE NEXT LEVEL WITH THE HELP YOU DESERVE
Whether you’re building your first robot, troubleshooting an ambitious prop, or diving into IoT, get expert guidance and
let's create something amazing together!
GET HELP