Step 12Your First Program
We won't mess with external clocks, we're just going to make an LED blink on and off at regular intervals. The code is attached below and is called "led_blinker.c", also in the folder are the accurate delay library we need for this project and a makefile. You should edit your makefile to correspond to the chip you're using - if you don't, it won't work when you upload it!
Lets take a look at the code then:
#include "adelay.h"
#include
First we declare what headers/libraries we're using. All you need for this is the AVR in/out library and the accurate delay library.
//io init
void init_io(void)
{
//All Ouputs on
DDRC = 0xff;
}
This function is called at the start of the program, it takes no input and returns no values, but it sets up the chip ready for input and output operations. DDRD refers to the direction register, in this case, we set it to the hex value of 0xFF which is, in binary, 1111 1111. This sets all the pins on Port C to be outputs. It may seem odd to have just one command inside a function, but this will get bigger as we add more code.
int main(void)
{
init_io();
while(1)
{
PORTC ^= (1 << 1);
PORTC ^= (1 << 2);
Delay_ms(1000);
}
return 1;
}
The main function is really simple, first we call the init function to get everything set up. Then we enter an infinite loop (AVRs should never exit the main function). The next function uses bitwise operators, if you intend to do any programming for embedded devices, you should get familiar with this. A good tutorial is here:. What the code does, in a pinch, is toggles the on off status for Pin 1 and 2 on Port C.
For some reason instructables formats ^ = into an exponent sometimes, so apologies. It also doesn't liked the < and > around includes (i guess it thinks it's a rogue html tag).
The Delay_ms(1000) function makes the program pause for 1000ms (or one second) and then continues.
So, it should be pretty obvious where this is going, there is an infinite loop (as while(1) is always true) and each time the loop iterates, it toggles the pin and delays a second, giving us a nice 1Hz blinker.
Use the makefile below, but rename it to 'makefile' first.
Next we'll send this to the programmer and upload it!
| « Previous Step | Download PDFView All Steps | Next Step » |
![]() |
Add Comment
|
























































