Select the clock speed. Figure 13 shows
16 MHz which is my favorite clock speed.
Hit Finish and you have now created a
project – you just need to add files to it!
Step Four: Write an AVR gcc program
and compile it.
This tutorial is about installing the tools to get
going with the AVR microcontrollers, not about
programming them. However, I feel you should
have something to make sure everything works.
LISTING 1
/*
test.c
*
Hello World for the embedded programmer.
*
Created on: Feb 9, 2010
Author: dlc
*/
#include <avr/io.h>
//Takes care of ALL I/O definitions
void init(void)
{
DDRB = 0xFF;
DDRC = 0xFF;
DDRD = 0xFE;
//all of port B is outputs
//all of port C is outputs
//RxD is an input, rest outs
ACSR = 0x80;
//Turn off analog comparitor
TCCR2A = 0x00;
TCCR2B = 0x04;
//Just a timer
//prescale 16MHz by 64 for 1.024mS/256
}
void waitms(unsigned int d)
/*
a ms timer routine.
*/
{
int delay;
for (delay=0; delay<d; delay++)
{
TCNT2 = 1;
while(TCNT2);
}
//wait for a rollover
}
int main(void)
{
init();
//Set up our processor
PORTB = 0x02;
//Turn on LED on PORTB.B1
while(1)
{
PORTB = 0x00;
waitms(500);
PORTB = 0x02;
waitms(200);
}
//blink LED forever
}
So, with that in mind, here is the embedded
world’s version of everybody’s first program,
“Hello World.” It simply blinks an LED. Refer to
Listing 1 for this discussion.
Let’s look at this simple program, function by
function. First, init(). The DDRB, DDRC, and DDRD
are the Data Direction Register B/C/D. These registers
define whether an I/O pin is an input or an output.
Each bit in the register corresponds to an I/O line.
A logical ‘0’ in a bit means that this line is an input;
a ‘1’ means it is an output. Notice that I set
everything to be an output. This does two things:
First, it makes it easy
to turn on an LED.
The second reason
comes from being a
professional embedded
engineer. We tend to
make any unused I/O
line an output so that
we avoid generating
“noise” on an input
that can make a system
unstable. The other
way to avoid this noise
is to tie said I/O lines to
either Vcc or ground,
and make the pin an
input. Without generic
boards, it makes more
sense to make the pin
an output if it’s not
being used. The ACSR
register defines the
use of the analog
comparator module. If
we don’t turn this off,
it will interfere with the
digital functions on
those I/O lines. Get into
the habit of looking for a
comparator on your micros
and turning them off!
Lastly, we
configure TCCR2A and
TCCR2B. These are
the Timer/Counter
Configuration Registers
for Timer2 in the
ATMEGA168 and
ATMEGA328. This is
an eight-bit timer that
can be used for PWM.
In this case, we’re
configuring it as a
simple timer. The 0x04
18 SERVO 04.2010