Thursday, 23 June 2016

Basics of Embedded C Program and Programming Structure for Beginners

Embedded C Programming is the soul of the processor functioning inside each and every embedded system we come across in our daily life, such as mobile phone, washing machine, and digital camera.
Each processor is associated with an embedded software. The first and foremost thing is the embedded software that decides functioning of the embedded system. Embedded C language is most frequently used to program the microcontroller.
Embedded C Programming
Embedded C Programming
Earlier, many embedded applications were developed using assembly level programming. However, they did not provide portability. This disadvantage was overcome by the advent of various high level languages like C, Pascal, and COBOL. However, it was the C language that got extensive acceptance for embedded systems, and it continues to do so. The C code written is more reliable, scalable, and portable; and in fact, much easier to understand.

About C Language

C language was developed by Dennis Ritchie in 1969. It is a collection of one or more functions, and every function is a collection of statements performing a specific task.
C language is a middle-level language as it supports high-level applications and low-level applications. Before going into the details of embedded C programming, we should know about RAM memory organization.

Salient features of the language

  • C language is a software designed with different keywords, data types, variables, constants, etc.
  • Embedded C is a generic term given to a programming language written in C, which is associated with a particular hardware architecture.
  • Embedded C is an extension to the C language with some additional header files. These header files may change from controller to controller.
  • The microcontroller 8051 #include<reg51.h> is used.
The embedded system designers must know about the hardware architecture to write programs. These programs play prominent role in monitoring and controlling external devices. They also directly operate and use the internal architecture of the microcontroller, such as interrupt handling, timers, serial communication and other available features.

Differences between C and Embedded C

Differences between C and Embedded C
Differences between C and Embedded C

The basic additional features of the embedded software

Data types
The data type refers to an extensive system for declaring variables of different types like integer, character, float, etc. The embedded C software uses four data types that are used to store data in the memory.
The ‘char’ is used to store any single character; ‘int’ is used to store integer value, and ‘float’ is used to store any precision floating point value.
The size and range of different data types on a 32-bit machine is given in the following table. The size and range may vary on machines with different word sizes.
Data types
Data types
Keywords
There are certain words that are reserved for doing specific tasks. These words are known as keywords. They are standard and predefined in the Embedded C.
Keywords are always written in lowercase. These keywords must be defined before writing the main program. The basic keywords of an embedded software are given below:
Keywords
Keywords
sbit: This data type is used in case of accessing a single bit of SFR register.
  • Syntax: sbit variable name = SFR bit ;
  • Ex: sbit a=P2^1;
  • Explanation: If we assign p2.1 as ‘a’ variable, then we can use ‘a’ instead of p2.1 anywhere in the program, which reduces the complexity of the program.
Bit: This data type is used for accessing the bit addressable memory of RAM (20h-2fh).
  • Syntax: bit variable name;
  • Ex: bit c;
  • Explanation: It is a bit sequence setting in a small data area that is used by a program to remember something.
SFR: This data type is used for accessing a SFR register by another name. All the SFR registers must be declared with capital letters.
  • Syntax: SFR variable name = SFR address of SFR register;
  • Ex: SFR port0=0x80;
  • Explanation: If we assign 0x80 as ‘port0’, then we can use 0x80 instead of port0 anywhere in the program, which reduces the complexity of the program.
SFR Register: The SFR stands for ‘Special Function Register’. Microcontroller 8051 has 256 bytes of RAM memory. This RAM is divided into two parts: the first part of 128 bytes is used for data storage, and the other of 128 bytes is used for SFR registers. All peripheral devices like I/O ports, timers and counters are stored in the SFR register, and each element has a unique address.

The Structure of an Embedded C Program

  • comments
  • preprocessor directives
  • global variables
  • main() function
{
  • local variables
  • statements
  • …………..
  • …………..
}
  • fun(1)
{
  • local variables
  • statements
  • …………..
  • …………..
}
Comments: In embedded C programming language, we can place comments in our code which helps the reader to understand the code easily.
C=a+b; /* add two variables whose value is stored in another variable C*/
Preprocessor directives: All the functions of the embedded C software are included in the preprocessor library like “#includes<reg51.h>, #defines”. These functions are executed at the time of running the program.
Global variable
A global variable is a variable that is declared before the main function, and can be accessed on any function in the program.
Global variable
Global variable
Local variable
A local variable is a variable declared within a function, and it is valid only to be used within that function.
Local variable
Local variable
Main () function
The execution of a program starts with the main function. Every program uses only one main () function.

Advantages of embedded C program

  • Its takes less time to develop application program.
  • It reduces complexity of the program.
  • It is easy to verify and understand.
  • It is portable in nature from one controller to another.

Examples of a few Embedded C Programs

The following are a few simple Embedded C programs used for microcontroller-based projects.
Example-1
Example-1
Example-2
Example-2
Example-3
Example-3
Example-4
Example-4
We hope that we have been successful in providing an easy and approachable way for the beginners of Embedded C programming. Better understanding of the Embedded C programming is the most essential prerequisite for designing embedded based projects. In addition to this, a better understanding and proper knowledge about embedded C programming help students immensely in the selection of a rewarding career.
We encourage and welcome queries, suggestions and comments from our readers. Therefore, you can post your queries and feedback about this article in the comments section given below. Follow the below link for: Solderless projects

Introduction to Keil C

Introduction to Keil C

The use of C language to program microcontrollers is becoming too common. And most of the time its not easy to buld an application in assembly which instead you can make easily in C. So Its important that you know C language for microcontroller which is commonly known as Embedded C. As we are going to use Keil C51 Compiler, hence we also call it Keil C.

Keywords

Keil C51 compiler adds few more keywords to the scope C Language:
_at_farsbit
alienidatasfr
bdatainterruptsfr16
bitlargesmall
codepdata_task_
compact_priority_using
datareentrantxdata
data/idata
Description: The variable will be stored in internal data memory of controller. example:
  1. unsigned char data x;
  2. //or
  3. unsigned char idata y;
bdata
Description: The variable will be stored in bit addressable memory of controller. example:
  1. unsigned char bdata x;
  2. //each bit of the variable x can be accessed as follows
  3. x ^ 1 = 1; //1st bit of variable x is set
  4. x ^ 0 = 0; //0th bit of variable x is cleared
xdata
Description: The variable will be stored in external RAM memory of controller. example:
  1. unsigned char xdata x;
code
Description: This keyword is used to store a constant variable in code memory. Lets say you have a big string which is not going to change anywhere in program. Wasting ram for such string will be foolish thing. So instead we will make use of the keyword "code" as shown in example below. example:
  1. unsigned char code str="this is a constant string";
pdata
Description: This keyword will store the variable in paged data memory. This keyword is used occasionally. example:
  1. unsigned char pdata x;
_at_
Description: This keyword is used to store a variable on a defined location in ram. example:
  1. unsigned char idata x _at_ 0x30;
  2. // variable x will be stored at location 0x30
  3. // in internal data memory
sbit
Description: This keyword is used to define a special bit from SFR (special function register) memory. example:
  1. sbit Port0_0 = 0x80;
  2. // Special bit with name Port0_0 is defined at address 0x80
sfr
Description: sfr is used to define an 8-bit special function register from sfr memory. example:
  1. sfr Port1 = 0x90;
  2. // Special function register with name Port1 defined at addrress 0x90
sfr16
Description: This keyword is used to define a two sequential 8-bit registers in SFR memory. example:
  1. sfr16 DPTR = 0x82;
  2. // 16-bit special function register starting at 0x82
  3. // DPL at 0x82, DPH at 0x83
using
Description: This keyword is used to define register bank for a function. User can specify register bank 0 to 3. example:
  1. void function () using 2
  2. {
  3. // code
  4. }
  5. // Funtion named "function" uses register bank 2 while executing its code
interrupt
Description: This keyword will tells the compiler that function described is an interrupt service routine. C51 compiler supports interrupt functions for 32 interrupts (0-31). Use the interrupt vector address in the following table to determine the interrupt number.
center

Vector Address Locations

example:
  1. void External_Int0() interrupt 0
  2. {
  3. //code
  4. }

Memory Models

There are three kind of memory models available for the user:
Small
All variables in internal data memory.
Compact
Variables in one page, maximum 256 variables (limited due to addressing scheme, memory accessed indirectly using r0 and r1 registers);
large
All variables in external ram. variables are accessed using DPTR.
Depending on our hardware configuration we can specify the momory models as shown below:
  1. //For Small Memory model
  2. #pragma small
  3. //For Compact memory model
  4. #pragma compact
  5. //For large memory model
  6. #pragma large

Pointers in Keil C

Pointers in keil C is are similar to that of standard C and can perform all the operations that are available in standard C. In addition, keil C extends the operatability of pointers to match with the 8051 Controller architecture. Keil C provides two different types of pointers:
  • Generic Pointers
  • Memory-Specific Pointers

Generic Pointers

Generic Pointers are declared same as standard C Pointers as shown below:
  1. char *ptr; //Character Pointer
  2. int *num; //Integer Pointer
Generic pointers are always stored using three bytes. The first byte is the memory type, the second byte is the high-order byte of the offset, and the third byte is the low-order byte of the offset. Generic pointers maybe used to access any variable regardless of its location.

Memory-Specific Pointers

Memory specific pointers are defined along with memory type to which the pointer refers to, for example:
  1. char data *c;
  2. //Pointer to character stored in Data memory
  3. char xdata *c1;
  4. //Pointer to character stored in External Data Memory.
  5. char code *c2;
  6. //Pointer to character stored in Code memory
As Memory-Specific pointers are defined with a memory type at compile time, so memory type byte as required for generic pointers is not needed. Memory-Specific pointers can be stored using 1 byte (for idata, data, bdata and pdata pointers) or 2 bytes (for code and xdata pointers).
The Code generated by keil C compiler for memory-specific pointer executes mroe quickly than the equivalent code generated for a generic pointer. This is because the memory area accessed by the pointer is known at the compile time rather at run-time. The compiler can use this information to optimize memory access. So If execution speed is your priority then it is recommended to use memory-specific pointers. Generic pointers and Memory-Specific pointers can be declared with memory area in which they are to be stored. For example:
  1. //Generic Pointer
  2. char * idata ptr;
  3. //character pointer stored in data memory
  4. int * xdata ptr1;
  5. //Integer pointer stored in external data memory
  6. //Memory Specific pointer
  7. char idata * xdata ptr2;
  8. //Pointer to character stored in Internal Data memory
  9. //and pointer is going to be stored in External data memory
  10. int xdata * data ptr3;
  11. //Pointer to character stored in External Data memory
  12. //and pointer is going to be stored in data memory

Functions in Keil C

Keil C compiler provides number of extensions for standarad C function declerations. These extensions allows you to:
  • Specify a function as an interrupt procedure
  • Choose the register bank used
  • Select memory model

Function Declaration

[Return_type] Fucntion_name ( [Arguments] ) [Memory_model] [reentrant] [interrupt n] [using n]
Return_type
The type of value returned from the function. If return type of a function is not specified, int is assumed by default.
Function_name
Name of function
Arguments
Arguments passed to function
Optional Stuff
These are options that you can specify along with function declaration. Memory_model: explicit memory model (Large, Compact, Small) for the function. Example:
  1. int add_number (int a, int b) Large
reentrant
To indicate if the function is reentrant or recursive. This option is explained later in the tutorial.
interrupt
Indicates that function is an interrupt service routine. This option is explained later in the tutorial.
using
Specify register bank to be used during function execution. We have three register banks in 8051 architecture. These register banks are specified using number 0 for Bank 0 to 3 for Bank 3 as shown in example
  1. void function_name () using 2
  2. {
  3. //function uses Bank 2
  4. //function code
  5. }
Interrupt Service Routines
A function can be specified as an interrupt service routine using the keyword interrupt and interrupt number. The interrupt number indicates the interrupt for which the function is declared as service routine.
Following table describes the default interrupts:
center

8051 Interrupt vector

As 8051 vendors create new parts, more interrupts are added. Keil C51 compiler supports interrupt functions for 32 interrupts (0-31). Use the interrupt vector address in the following table to determine the interrupt number.
center

Interrupt vector

The interrupt function can be declared as follows:
  1. void isr_name (void) interrupt 2
  2. {
  3. // Interrupt routine code
  4. }
Please make sure that interrupt service routines should not have any arguments or return type except void.
Reentrant Functions
In ANSI C we have recursive function, to meet the same requirement in embedded C, we have reentrant function. These functions can be called recursively and can be called simultaneously by two or more processes. Now you might be thinking, why special definition for recursive functions?
Well you must know how these functions work when they are called recursively. when a function is running there is some runtime data associated with it, like local variables associated with it etc. when the same function called recursively or two process calls same function, CPU has to maintain the state of function along with its local variables. Reentrant functions can be defined as follows:
  1. void function_name (int argument) reentrant
  2. {
  3. //function code
  4. }
Each reentrant function has reentrant stack associated with it, which is defined by startup.A51 file. Reentrant stack area is simulated internal or external memory depending upon the memory model used:
  • Small model reentrant functions simulate reentrant stack in idata memory.
  • Compant model reentrant functions simulate reentrant stack in pdata memory.
  • Large model reentrant functions simulate reentrant stack in xdata memory.
Real-time Function Tasks
Keil or C51 provides support for real-time operating system (RTOS) RTX51 Full and RTX51 Tiny. Real-time function task are declared using _task_ and _priority_ keywords. The _task_ defines a function as real-time task. The _priority_ keyword specify the priority of task.
Fucntions are declared as follows:
  1. void func (void) _task_ Number _priority_ Priority
  2. {
  3. //code
  4. }
where:
Number
is task ID from 0 to 255 for RTX51 Full and 0 to 15 for RTX51 Tiny.
Priority
is priority of task.
Real-time task functions must be declared with void return type and void argument list (say no arguments passed to task function).

Writing First C program in Keil

Basic of a C program

As we already discussed, 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.
  1. void main()
  2. {
  3. //Your one time initialization code will come here
  4. while (1) {
  5. //while 1 loop
  6. //This loop will have all your application code
  7. //which will run infinitely
  8. }
  9. }
When we are working on controller specific code, then we need to add header file for that controller. I am considering you have already gone through "Keil Microvision" tutorial. After project is created, add the C file to project. Now first thing you have to do is adding the header file. All you have to do is right click in editor window, it will show you correct header file for your project.
Figure below shows the windows context for adding header file to your c file.
center

Include Header file in Keil

Writing Hardware specific code

In harware specific code, we use hardware peripherals like ports, timers and uart etc. Do not forget to add header file for controller you are using, otherwise you will not be able to access registers related to peripherals. Lets write a simple code to Blink LED on Port1, Pin1.
  1. #include <REGx51.h>
  2. //header file for 89C51
  3. void main()
  4. {
  5. //main function starts
  6. unsigned int i;
  7.  
  8. //Initializing Port1 pin1
  9. P1_1 = 0; //Make Pin1 o/p
  10.  
  11. while (1) {
  12. //Infinite loop main application
  13. //comes here
  14. for(i=0;i<1000;i++)
  15. ; //delay loop
  16.  
  17. P1_1 = ~P1_1;
  18. //complement Port1.1
  19. //this will blink LED connected on Port1.1
  20. }
  21. }
You can now try out more programs. "Practice makes a man perfect".

Writing C and Assembly together

Interfacing C program to Assembler

You can easily interface your programs to routines written in 8051 Assembler. All you need to do is follow few programming rules, you can call assembly routines from C and vice-versa. Public variables declared in assembly modules are available to your C program.
There maybe several reasons to call an assembly routine like faster execution of program, accessing SFRs directly using assembly etc. In this part of tutorial we will discuss how to write assembly progarms that can be directly interfaced with C programs.
For any assembly routine to be called from C program, you must know how to pass parameters or arguements to fucntion and get return values from a function.

Segment naming

C51 compiler generates objects for every program like program code, program data and constant data. These objects are stored in segments which are units of code or data memory. Segment naming is standard for C51 compiler, so every assembly program need to follow this convention.
Segment names include module_name which is the name of the source file in which the object is declared. Each segment has a prefix that corresponds to memory type used for the segment. Prefix is enclosed in question marks (?). The following is the list of the standard segment name prefixes:
center

C51 module prefix

Data Objects
Data objects are the variables and constants you declare in your C programs. The C51 compiler generates a saperate segment for each memory type for which variable is declared. The following table lists the segment names generated for different variable data objects. Data objects segment prefix
center

Data Segment Prefix

Program Objects
Program onjects includes code generated for C programs functions by C51 compiler. Each function in a source module is assigned a separate code segment using the ?PR?function_name?module_namenaming convention. For example, for a function name send_char in file name uart.c will have a segment name of ?PR?SEND_CHAR?UART.
C51 compiler creates saperate segments for local variables that are declared within the body of a function. Segment naming conventions for different memory models are given in following tables:
center

Small model segment naming convention

center

Compact model segment naming convention

center

Large model segment naming convention

Function names are modified slightly depending on type of function (functions without arguments, functions with arguments and reentrant functions). Following tables explains the segment names:
center

function segment naming convention

Advanced C programming

Function Parameters

C51 make use of registers and memory locations for passing parameters. By default C function pass up to three parameters in registers and further parameters are passed in fixed memory locations. You can disable parameter passing in register using NOREGPARMS keyword. Parameters are passed in fixed memory location if parameter passing in register is disabled or if there are too many parameters to fit in registers.

Parameter passing in registers

C functions may pass parameter in registers and fixed memory locations. Following table gives an idea how registers are user for parameter passing.
center

parameter passing to functions

Following example explains a little more clearly the parameter passing technique:
center

example parameter passing to functions

Parameter passing in Fixed Memory Locations

Parameters passed to assembly routines in fixed memory lcoation use segments named
?function_name?BYTE
All except bit parameters are defined in this segment.
?function_name?BIT
Bit parameters are defined in this segment.
All parameters are assigned in this space even if they are passed using registers. Parameters are stored in the order in which they are declared in each respective segment.
The fixed memory locations used for parameters passing may be in internal data memory or external data memory depending upon the memory model used. The SMALL memory model is the most efficient and uses internal data memory for parameter segment. The COMPACT and LARGE models use external data memory for the parameter passing segments.

Fucntion Return Values

Function return values are always passed using CPU registers. The following table lists the possible return types and the registers used for each.
center

function return values

Example
Following example shows how these segment and function decleration is done in assembler.
  1. ;Assembly program example which is compatible
  2. ;and called from any C program
  3. ;lets say asm_test.asm is file name
  4. name asm_test
  5. ;We are going to write a function
  6. ;add which can be used in c programs as
  7. ; unsigned long add(unsigned long, unsigned long);
  8. ; as we are passing arguments to function
  9. ;so function name is prefixed with '_' (underscore)
  10. ;code segment for function "add"
  11. ?PR?_add?asm_test segment code
  12. ;data segment for function "add"
  13. ?DT?_add?asm_test segment data
  14. ;let other function use this data space for passing variables
  15. public ?_add?BYTE
  16. ;make function public or accessible to everyone
  17. public _add
  18. ;define the data segment for function add
  19. rseg ?DT?_add?asm_test
  20. ?_add?BYTE:
  21. parm1: DS 4 ;First Parameter
  22. parm2: ds 4 ;Second Parameter
  23. ;either you can use parm1 for reading passed value as shown below
  24. ;or directly use registers used to pass the value.
  25. rseg ?PR?_add?asm_test
  26. _add:
  27. ;reading first argument
  28. mov parm1+3,r7
  29. mov parm1+2,r6
  30. mov parm1+1,r5
  31. mov parm1,r4
  32. ;param2 is stored in fixed location given by param2
  33. ;now adding two variables
  34. mov a,parm2+3
  35. add a,parm1+3
  36. ;after addition of LSB, move it to r7(LSB return register for Long)
  37. mov r7,a
  38. mov a,parm2+2
  39. addc a,parm1+2
  40. ;store second LSB
  41. mov r6,a
  42. mov a,parm2+1
  43. addc a,parm1+1
  44. ;store second MSB
  45. mov r5,a
  46. mov a,parm2
  47. addc a,parm1
  48. ;store MSB of result and return
  49. ;keil will automatically store it to
  50. ;varable reading the resturn value
  51. mov r4,a
  52. ret
  53. end
Now calling this above function from a C program is very simple. We make function call as normal function as shown below:
  1. extern unsigned long add(unsigned long, unsigned long);
  2. void main()
  3. {
  4. unsigned long a;
  5. a = add(10,30);
  6. //a will have 40 after execution
  7. while(1);
  8. }