top of page

Build a Robot: TIMER code

Anchor 1

So, we are going to learn the following with our Timer code:

  1. Glow 2 LEDs with PWM ON and OFF.

  2. Hook up 2 servos (which also use PWM) to move the jaw up and down with a push button.

This lesson will focus on the first and the next lesson will focus on the second.


This will look fairly complicated but understanding Timers and doing PWM this early at this deep level will propel you forward much faster as it is used in MANY programs to do various tasks.


It is NOT optional.


The first thing you need to know is the AVR 328p chip has 3 separate Timers built in.



There are two 8-bit resolution timers and one 16-bit resolution timer.

The 8-bit timers are great for time clocks and most processes you can imagine.

The 16-bit timer is great for measuring something that needs double the accuracy like reaction time or some high speed sensor.

Later I will show you how to look all of this up in the Datasheet.

These timers can be thought of as 3 different alarm clocks.

We use these Timers to set the frequency, or tempo, for certain tasks and sensors.

We can set up special triggers called interrupts to occur with these Timers.

For example, when the time runs through, aka when all the bits count through the Timer (0-255) on the 8-bit timers, an interrupt service routine can be triggered to to perform some task.

Do you see how useful these two working together can be?


For our robot mask we can use one of the Timers to generate PWM which stands for...

That's right: Pulse Width Modulation.

Pulse means ON then OFF and ON then OFF again.

Width means how WIDE the pulse is, aka how long we put out electricity on 1 pin on the chip.

Modulation means to change or vary.

I hope this is clearer to you than it was to me when I first came across this information!

If not, do what I did and take a break, walk away, come back and reread or try to draw it out, etc.

You WILL understand it! Give yourself a chance to digest it slowly.

Take a look at the 2-D illustration below.

PWM Diagram


Look at what happens when we implement code that increases the duration(width) of each pulse. 


Remember, the frequency remains the same.

When we want our LED eyes to glow to ON instead of just turn on we set up our Timer0 and then write code for the duration of the ON status to increase each time it counts through.

The 8-bit timer will count through all 256 bits starting with 0 and ending with 255.

After each time it counts through we can write simple code to increase the duration the electricity is output on the pin associated with the timer.

So, in the beginning the pin is OFF.

The Timer counts through all 256 steps then starts again at 0.

The second time through it will turn on for 1 tick of the clock.

The third time through it will turn on for 2 ticks.

The fourth time 3 ticks.

We do this all the way up to 255 ticks.

In other words, when you see an LED glow on you are seeing it turn on longer and longer VERY quickly.

It is so fast your brain cannot distinguish between the ON state and OFF state.

This is very very easy to code and I will show you the code below.

First, let's take a look at what is happening with this PWM illustration below.




We can also use this concept to rev up or rev down a DC motor instead of just turn it ON.


We will use the 8-bit resolution Timer0.


Remember 0 really means 1 in the computer world, but not always which can be annoying...yeah yeah...I know...

Timer0 is an 8 bit timer.

Question: What does 8 bits look like on paper?

That's right:


Like I introduced a minute ago, our Timer0 will flip through every available bit counting from 0 to the maximum 255.

Because we include 0 that means it counts through 256 steps.

Imagine the bits being flipped like an abacus slide rule calculator.

0b00000001        =      1

0b00000010        =      2

0b00000011        =      3

0b00000100        =      4

0b00000101        =      5

0b00000110        =      6

0b00000111        =      7

0b00001000        =     8


The speed at which it goes through depends upon the speed at which the AVR chip is clocked.


Remember it comes from the factory at 1/8 the speed it is capable of (to save battery and prolong its life) which you can CHANGE both at the top of your code or "permanently" by entering in the correct "FUSE bit" combination of letters and numbers which you can find online very easily.

An Arduino Uno uses a crystal oscillator to achieve a faster clock speed at 16 mHZ which is blazingly have no idea really how fast that is...It speeds up its internal oscillator clock so fast that you would appear to almost never move.

It's THAT FAST so have some respecc.

Here is the basic overview of how to implement this Timer function built into our chips:

1.  Set up a function to initialize the Timer with the specific Timer's name

2.  Set correct bits associated with the frequency/tempo/flavor of PWM you want, ex. Normal or FAST or Clear Timer on Compare Match (CTC) Mode.

3.  Set correct bits associated with your desired prescaler which means how much you want to divide that clock speed by (don't worry about this yet but know it exists and is commonly played with for different results)

4.  Set correct bits associated with the output pin assigned to that particular Timer.

**NOTE: It IS possible to make any pin perform PWM (once again, know this exists but is not necessary to learn yet...just get excited with all the possibilities these chips can offer because its nothing short of magic)

At first, this will not make sense.

After a second and third look, it may still not make sense.

So, hopefully this explanation will help.

The microchips are like an old switchboard for a telephone company.

There are switches to be flipped and connections made with wires by you and by transistors within the chip.


When certain switches are flipped, certain clocks run through each tick and math is performed, electricity is sent along certain paths to other switches and clocks or outside of the box via a metal pin.

When you start using the datasheet (which is like an encyclopedia not a "how to") you will start seeing through the illusion and realize how simple this all really is.

That is when you will be POWERFUL.

When you are powerful you will start reading the datasheet like a novel next to a fireplace with some cozy slippers and your favorite chocolate chip cookies and milk.

Then you will master the slightly more complex capabilities within these chips and bring some incredible automated designs to life.

Take a moment to reflect on this.


Not much has changed over the years

You set up the Timer0 function at the top of your code before the int main (void) {    } section, or main for short.

In main, you call that function,"HEY! Timer0 function get over here!", by typing its name like this:



That turns that function ON as the code starts when the chip is powered ON.

Now it's time for a deep dive into what goes on within the Timers in the chip.

Refer to the diagram below, you NEED to know this and don't worry, this is arguably the hardest yet most important part of programming robots and electronics you will learn.

Once this starts to make sense in your head you will be able to focus even better on the coding part of your projects.

Timer flow chart.png

You set up the Timer0 function at the top of your code before the int main (void) {    } section, or main for short.

In main, you call that function,"HEY! Timer0 function get over here!", by typing its name like this nameOfYourTimerFunction();

That turns that function ON as the code starts when the chip is powered ON.

Remember our Timer0 function was output to the dedicated PWM pin associated with OCR0A?

On the 328p pinout diagram it shows as pin PD6.

In the loop area of our code is where we set the OCR0A to a certain value.

It will use the timer we set up to turn on and off at the intervals/frequency we specified after counting up to the  maximum value we set in OCR0A.

Here is the code for how to set up the Timer0.


I have included some comments in green for you.

The first thing you will notice is the label 'static inline void' followed by the name I made up.

I decided to name my timer initializing code 'initTimer0'.

It doesn't need any parameters so we follow the name with '(void)'.

After that we open the door with {

The code you see inside are just the switches that need to be turned on in this room to set the prescaler, the datasheet says we have to go into the TCCR0B register and flip the CS00 and CS01 bits to ON.

Just like turning on the lights for the parts of your room you will be in.

We do this by typing TCCR0B |= (1 << CS00) | (1 << CS01)

Here is how we call that Timer0.


Here is the code for the actual WORK to be performed using our 8-bit Timer0.


If you don't understand exactly what is happening here don't worry.  This is all EXTREMELY complicated.

That is why I wanted to start this entire site.

It is a guide for myself that I wish I had years ago when I started.

Just take a few deep breaths and look over it, STUDY it, over periods of time.

Then it will click.

If you need additional help:

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.


You have seen an example of code that simply sets up a timer which has a frequency that is called and utilized to count through all 8 bits (aka 1 byte, aka 0b00000000) each time it counts through the duration the pin attached to the LED is held ON longer by 1 more clock tick.


Timers and interrupts are VERY difficult to understand if you have ZERO prior programming or electronics experience but you WILL understand, trust me.


Be easy on yourself.


These are POWERFUL tools that you will use in almost every project including motors of all kinds, sensors, and SERVOS!

Speaking of which it is time to finally put everything together.


I will be teaching you how to use the timer and interrupts to control a servo via a push button and even a simple joystick!

You will see the entire code and explanations for each and we will see every step to bringing your robot mask to life.

Get ready to take notes and draw some concepts!

해당 언어로 게시된 게시물이 없습니다.
게시물이 게시되면 여기에 표시됩니다.
bottom of page