©2019 Robotics for COMPLETE Beginners


Build a Robot:

Servo Code


Never Miss a Note.


The Tower Pro SG90 Micro Servo.

Stylish, Elegant and CHEAP.

Disclaimer:  Contact your internet auction site dealer for details and availability.  Not all servos are created equally.  Some may encounter serious cases of the "jitters" and the user will be responsible for figuring that out. Micro servos should not be used for heavy loads or serious builds.  To do that buy a big one that takes more juice or better yet buy brushless servos. Warning: Users may cry and fall into fits of rage when they mix up the wiring or code and forget that this is a complicated machine.  Noone else will be responsible if users connect all kinds of weird things to the servo which may cause injury or harm.  User discretion is strongly advised.  Seriously, don't go to prison.

This lesson is going to be much more in depth and informative than the first servo lesson you had.


By now you should have some basic concept of how they work but it is actually much more complicated.


Luckily for you, I can help you understand in one lesson.


Servo motors, cousins of DC and Stepper motors in the motor family are very handy tools to put objects in motion and get a job done.


Servos are what most beginners want to learn how to control when it comes to building robots and for good reason.

They have a simple movement, rotating a shaft clockwise or counterclockwise.

A lever, arm, or gear is often attached to the top of that shaft and by rotating it robotic eyes can move like real eyes, arms can move and artificial hands with the help of strings can appear to move like real hands.

Servos are powerful and will open your mind to many great possibilities and creations!

The problem with servos is that setting them up just to spin the way they do is very complicated and will often stump beginner robotics and electronics learners.

I have been slapped in the ego by servos many times and will do my best to explain how to use them in the simplest way possible because I know you want to use them in your projects!

How do they work?

Just like transistors and DC motors there are many types of servos.

Let's look at what is similar in all of them first.

Micro Servo piggy-backing larger higher torque servo.

Notice it only has 2 wires, positive and ground, no signal wire but it does connect to a microcontroller.

Servos are simply a DC motor that is attached to various gears to translate their weak torque and high speed into higher torque and lower speed.


Servos generally rotate up to 180 degrees or half a circle.  There are servos that can rotate continuously but you could do the job similarly with a DC motor and some gears or even better a highly accurate stepper motor with some gears like you can see in 3D printers and CNC machines.

Servos are what turns the front wheels in your RC cars and moves the ailerons up and down on your RC planes.

They also control the pitch and roll on RC helicopters.

A servo is a "position seeking device".


It has an appetite for adventure.

When put in the right mood it moves in pursuit of its new found dream.

Once it arrives at its dream destination it stops rotating and enjoys its new home, taking a rest.

There is one other part of the servo that is the key to it working, a microchip.

There is a very small microchip board that controls the servo movements.

This microchip is always listening to an input telephone line that is connected to a microcontroller like a PIC, AVR or ARM microcontroller, etc.

The AVR or other type of microcontroller sets a timer to operate at the same frequency that the servo microchip was set at in it's factory when it was made.

The microcontroller has code written by you to send pulses for a certain duration out on a pin that you choose to send them out on.

PWM again here, remember the timer lesson?

It works in almost the same exact way as the LED glow example.

The microcontroller has a beat like a bass drum at the same intervals that the servo is beating its own bass drum.

The microcontroller then sends out a pulse of electricity at each interval, kind of like playing a guitar or piano note.

The length of time that the pulse stays on for determines the direction the servo will rotate!

Read that one more time.

Again, review the Timer and PWM concepts if you need to!

PWM is the most crucial concept for you to gain confidence to build almost anything.

See how ingenious this servo idea is?

See how simple the concept of a servo it is?

See how complex it is to set it up?

You will get good with practice, repetition, repetition, repetition.

Imagine the servo like spaceship.

It receives orders from space command, plots a course to a new planet in space and immediately takes off.

Once it arrives at its destination it shuts down its warp drive and lands on the planet until new orders are received from space command.

As long as the signal is constantly coming in from the microcontroller into the servo's microcontroller and no new duration is specified it will hold its position.

You can see this fact by trying to push the servo lever around with your hand.

It will likely not budge at all.  It is a very obedient Space Force Soldier.

Most small, RC type servos operate at a frequency of about 20milliseconds (20ms).

You just need to set up your PWM on the AVR chip in your C program code to operate at that frequency.

Usually, if you look up the datasheet for any RC type servo you will see they turn clockwise and counterclockwise depending on if a 1ms long pulse of electricity comes into the servo or a 2ms long pulse comes in.

Read that again.

So, if the guitar note is 1ms long it will turn left and if the guitar note is 2ms long it will turn right.

1ms pulse from AVR microcontroller turns it left (or right, depends on your servo..)

2ms pulse from AVR microcontroller turns it right (or left, depends on your servo..)

I hope this is crystal clear to you by now.

When there is no change in the pulse durations coming in the servo will hold its current position.

If there are no pulses coming in at all on the line it will go back to the center.

Pretty cool, right?

Once you get the code flashed to your AVR chip and the servo moving you will want to play with the duration values and even the frequency to see how it affects the servo.

This sort of fine tuning can get rid of jitters in the servo which will occur in cheaper servos like the small, cheap and popular blue colored Tower Pro SG90.

In the advanced robot tutorials I will even show you how to change the direction a servo rotates, basically swapping directions for the 1ms or 2ms pulse coming in.

This will come in handy and is easy to do but not necessary to learn yet.

Let's keep this as simple as possible for now.

Servo Code

Ok, here is the demonstration code to get you started with servos.

Once again, I recommend backing up all correctly working code files somewhere separate from the folder where you have your code and hex files stored.


Nothing is worse than working out kinks in your code which sometimes takes weeks or months to finally sort out only to have it changed so much later on that you don't remember how you originally fixed it.

Or maybe your file gets deleted by accident etc.

Back up ALL of your successful code on a regular basis, even if it means copying your programs folder to a USB or other hard drive.

Ok!  Now onto the code, remember this is PWM again so you should start to remember a few pieces of code.

If not, don't worry you just need to repeat this demo code over and over until it starts to become clear in your mind!


Let's start from the top.

You will notice the #include files that you learned about in the C Programming lesson.

Then you will notice I put in a multi line comment using      /*    my warning about wiring here */

Remember, always make sure to include notes about the code especially when starting out.

Don't be afraid to make notes for every line of code even.


It will HELP you make sense and stay focused.

Ok, after the comments I left there is code to set up a timer which I called "initTimer1Servo".

Remember you can choose any name.

After that you need to set the speed of the Timer which is what TCCR1A and TCCR1B do.

You can see all this on the AVR datasheet.

The next line ICR1A which you can find in the datasheet as well is to set the frequency in terms of ms.

We set it at 2000ms which equates to 50 Hz which is the Hz that the Tower Pro SG90 servo operates at.

Ok, so the frequency will match the servo, great!


Next, we set the pins which will output the signal to our servo.


I chose PB1 and PB2.


Alright, so we have the Timer all set.

Next, we need to program our push buttons which will control the servo turning clockwise and counter-clockwise.

Don't worry, this is super easy and then we will be almost done!

Next, we need to set up our "Main" code with inits and then the "Loop" like you learned before.


Get my favorite books on programming AVR chips I use.

Equip yourself with the most dependable, no hassle, quality usb programmer I use daily.

Make sure you have a basic kit. Arduino is fine, it contains the removable AVR 328p chip we will use.


I started with something very similar.