- The first portion of a C program is usually a bunch of comments that describe the file. Usually this includes the name, author, and date of the file.
//***************************************
//***************************************
// AVRLIB-DEMO
// For avrlib and avrmini development board.
//
// File: button.c
// Author: Michael Gurevich
// Date: Sept. 22, 2002
// Modified: June 9, 2004
- Next are #includes. They tell the compiler where to look for other bits of code you are using that do not reside in this file. They are normally ".h" or header files that contain macros and function prototypes. Before a the .c file is compiled, the contents of the #includes are literally copied into the file.
#include <avr/io.h>
#include <avr/signal.h>
#include "global.h"
#include "timer.h"
- #defines are "macros". Before the program is compiled, the argument of the #define is simply substituted everywhere the name is used. They are handy for giving meaningful names to numbers and for changing a single value that may be used numerous times in a program without having to change every instance.
#define DEBOUNCE_THRESHOLD 1000
- Function prototypes give the name, arguments and return type of functions that will be used later in the program. They can be included in header files or in the .c file before the function is defined.
void checkButton(void);
- The main function is literally the main part of the code. There can only be one main function in the final compiled program. The code inside the main function is executed sequentially, one line at a time.
int main(void)
{
// set led pins (low 4 bits) as outputs,
// set button pins (high 4 bits) as inputs
outb(DDRD, 0x0F);
// Turn off LEDs by setting the low 4 bits
outb(PORTD, 0x0F);
// loop forever
while(1) {
// call the checkButton function
checkButton();
}
return 0;
}
- Finally, there are function definitions. These are pieces of code that are called from the main function or from other functions, that have a specific functionality that may want to be used over and over.
void checkButton(void) {
static u16 buttonDownCounter;
if (! bit_is_set(PIND,4)) {
if (buttonDownCounter++ == DEBOUNCE_THRESHOLD) {
cbi(PORTD,0);
}
}
else { //button is not pressed
buttonDownCounter = 0;
sbi(PORTD,0);
}
}