21
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.
Remember?
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 is HUNGRY.
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.
TRUST ME.
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 with the preamble at the top of our code:

We need to include the basic avr/io.h , util/delay.h , and avr/interrupt.h header files for all of the jobs we need completed.
Below that we can save time and typing numbers later by defining the length of the pulses that will be sent out on our pin connected to our servo.
I have named them simply clockwise, counterclockwise, and middle to make it easier for you to understand!
Next to each of these names I have assigned a number. These will be the length of the electrical pulses in ms.
Next, we need to set up a timer that will be fast enough to send out electrical pulses at 20ms which is how fast our servo is operating at. if we don't it will not move the way we want it to.
You can prove this by tapping 5v of electricity a few times to your signal line of your servo after you connect the positive and negative lines to a battery pack or usb power source.
You will see it move in only 1 direction because the servo has a chip inside it that tells it to move in that one direction for any electrical pulses that come in on that signal line that are slower than 2ms.
since we need very fast and accurate timing we can use the 16bit timer1 built into our chip.
16 bits is higher resolution than our 8 bit timers and this chip's 16 bit timer1 has some fast modes we need as well. it's all in the datasheet which you will eventually learn later on.
let's take a look at setting up this timer1 below.

This may start to look intimidating but the good news is you will be using this kind of code over and over again and all it is is turning on switches inside the chip to do the hard work for you!
Take a look at the notes in red.
You can learn which switches to flip by looking at the avr 328p datasheet. it has a few other models labeled on it but they are generally the same chip and have the same stuff going on inside.
TCCR1A and TCCR1B are the rooms I had to enter to turn on the switches WGM11, WGM12 and WGM13.
These are the waveform generation mode switches that when all three are turned on set the timer1 to fast mode.
Next, we turn on the prescaler in TCCR1B by flipping on CS10 this allows us to type in the next easy to read value of 20000 which is the frequency our chip operates at.
TIMER1 will count up to this 20000 value and it looks for it in a room called ICR1.
Next, we decide where we will send out our electrical pulses every 20000ms.
We go back into room TCCR1A and turn on COM1A1. This tells the chip we will send electricity out on OC1A.
If you look at the Atmega328p pinout diagram you will see OC1A is on pin PB1. That is 1 of 4 PWM enabled pins on the chip. You could use any of the others. Try and find them on the pinout and color them for later use!
Last, we set the Data Direction Register B which is the street that our PORTB pins have houses on. In PortB we wilL set that OC1A connected pin, PB1, to an OUTPUT state.
This is alot for beginners but don't worry, each time you look at it you will start to understand more and realize how simple it is.
Just. Flipping. Switches.
Next, let's set up a little dance routine for our servo and that way we don't have to type it out later in the code. By predefining routines like this we can declutter our actual code and play with these predefinied routines even. Get used to doing this, trust me it makes everything easier!

This is the actual code that will send the pulses to OCR1A which is connected to PB1.
Here you can see how it is defined and I gave it the name servoDemo.
Next, you can see the routine and the varying delay times I threw in there just to make things interesting. You can change these delay times yourself!
We will call this routine later in our loop.
First, we need to move to the second and third blocks of our code: main and Loop.

Notice I wrote "set the stage" as the comment in my main.
This is basically what Main is, a rolecall for everyone before the performance, setting your stage.
When your chip is powered on it will run through main code once only.
After that, it will go through the loop to the bottom and then go back to the top of loop and repeat forever.
I decided to set my servo to the middle position as you can see.
Then, I call on the Timer1Servo we set up in the preamble.
So, the chip boots up, Timer1 is all set up and ready to shoot out pulses on PB1 every 20ms and the servo goes to its middle position.
Next, is the loop.
All we do here is call on that dance routine we called servoDemo and the chip will carry this out till the end of time.
This is a very basic servo code and I HIGHLY recommend getting VERY familiar with it.
This took me forever to understand and it's easy to forget so make sure you come back and review this and it will make everything else easier because Timers are crucial to most electronic programming and any robot worth its salt is going to have a servo or 2. Or 20.
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.