Tuesday, August 18, 2009

SDCC - Small Device C Compiler

SDCC - Small Device C Compiler - is a free open source C compiler software for 8051 and a few other microcontrollers. Unlike SDCC, there are other popular commercially available compilers such as Keil that you can purchase. You can download a free evaluation version there but that trial version is limited to 2k byte code size. A good thing about SDCC is that you can get it for free at no cost. This post is just an overview of SDCC manual at http://sdcc.sourceforge.net/doc/sdccman.pdf. Writing and compiling of a few example C programs on Windows for 8051 are  also discussed.


Installing
Go to http://sdcc.sourceforge.net/ and download the setup program Run the setup program and follow the installation process.

Testing the SDCC Compiler
To test the installation of the compiler whether it is OK or not, go to command prompt and enter "sdcc -v". This should return sdcc's version number.

Example C Program
Type in the following example program using your favorite ASCII editor and save as led.c. This is an example C program for 8051 microcontroller to blink an LED connected to P3.4 pin.
#include<8052.h>
void main()
{
int i;
while(1)
{
P3_4=0;   //Output 0
for(i=0;i<30000;i++);  //delay loop
P3_4=1;   //Output 1
for(i=0;i<30000;i++);  //delay loop
}
}


Compiling and Getting Hex File
Go to the path where led.c is located and enter "sdcc led.c". If all goes well the compiler will link with the libraries and produce a led.ihx output file. You can enter "dir" to see if there is led.ihx file. After that, enter "packihx led.ihx>led.hex" to get the intel hex file that is suitable to download into your chip.

Projects with Multiple Source Files
SDCC can compile only ONE file at a time. Let us, for example, assume that you have a project containing the following file: main.c blink.c Type in the following example code in these files.
//File name: main.c
#include "blink.h"
void main()
{
while(1)
{
toggle();
delay();
}
}


//File name: blink.c
#include <8052.h>
#include "blink.h"
void toggle()
{
P3_4^=1;
}
void delay()
{
int i;
for(i=0;i<30000;i++); //delay loop
}


//File name: blink.h
void toggle();
void delay();

The files without main() function will need to be compiled separately with the commands: "sdcc -c blink.c". Then compile the source file containing the main() function and link the files together with the command- "sdcc main.c blink.rel". You will get main.ihx file and then you can get main.hex file as discussed before.