Pages

Friday, October 07, 2011

Writing First C in Keil Compiler

lets we do with keil compiler. Keil C is not much different from a normal C program. If you know assembly, writing a C program is not a problem, only thing you have to keep in mind is forget your controller has general purpose registers, accumulators or whatever. But do not forget about Ports and other on chip peripherals and related registers to them.

In basic C, all programs have atleast one function which is entry point for your application that function is named as "main" function. Similarly in keil, we will have a main function, in which all your application specific work will be defined. Lets move further deep into the working of applications and programs.

When you run your C programs in your PC or computer, you run them as a child program or process to your Operating System so when you exit your programs (exits main function of program) you come back to operating system. Whereas in case of embedded C, you do not have any operating system running in there. So you have to make sure that your program or main file should never exit. This can be done with the help of simple while(1) or for(;;) loop as they are going to run infinitely. Following layout provides a skeleton of Basic C program.

CODE:
void main(){
//Your one time initialization code will come here
        while(1){
                //while 1 loop
                //This loop will have all your application code
                //which will run infinitely
        }
}

and, for add , just right click, and choose insert include REGx51.h. Its very simple and easy,,,

lets do with practice
we try to make Blink LED on PORT1, Pin 1

CODE:
#include //header file for 89C51
void main(){
        //main function starts
        unsigned int i;
        //Initializing Port1 pin1
        P1_1 = 0; //Make Pin1 o/p
        while(1){
                //Infinite loop main application
                //comes here
                for(i=0;i<1000;i++)
                        ; //delay loop
                P1_1 = ~P1_1;
                //complement Port1.1
                //this will blink LED connected on Port1.1
        }
}
 
and then, build it to Hex first, and then download to your microcontroller. and look what happen with Port1 pin1. if your it not blink, check your circuit and your code.

HAVE FUN with MICROCONTROLLER... ^_^

0 comments:

Post a Comment