Monday, October 19, 2009

Basic example of writing C code for the 8051

/*************************************************************************
* basic.c - The basics of writing C code for the 8051 using the Keil
* development environment. In this case, a simple program will be
* constructed to make a binary counter on Port 0.
*/

/*
* As always with C, the included header files should come first. Most
* every project for the 8051 will want to include the file reg51.h. This
* header file contains the mapping of registers to names, such as setting
* P0 (port 0) to address 0x80. This allows the coder to use the keyword
* "P0" in their code whenever they wish to access Port 0. For the complete
* list of registers named, view the file.
*/

#include

/*
* Other header files may be included after reg51.h, including any headers
* created by the user.
*/

/*
* The C program starts with function main(). In the case of a program
* written using multiple .c files, main can only occur in one of them.
* Unlike in programming user applications for a standard computer, the
* main() function in a Keil program for the 8051 takes no inputs and
* returns no output, thus the declaration has implied void types.
*/

/*************************************************************************
* main - Program entry point
*
* INPUT: N/A
* RETURNS: N/A
*/

main()
{
unsigned int i; /* will be used for a delay loop */

/* First, Port 0 will be initialized to zero */

P0 = 0;

/*
* Now the counter loop begins. Because this program is intended
* to run in an embedded system with no user interaction, and will
* run forever, the rest of the program is placed in a non-exiting
* while() loop.
*/

while (1==1)
{
/*
* This is a very unpredictable method of implementing a delay
* loop, but remains the simplest. More reliable techniques
* can be done using the using the built-in timers. In this
* example, though, the for() loop below will run through 60000
* iterations before continuing on to the next instruction.
* The amount of time required for this loop varies with the
* clock frequency and compiler used.
*/

for (i = 0; i <>

/* Increment Port 0 */

P0 = P0 + 1;
}

}

0 comments:

Post a Comment