Beruflich Dokumente
Kultur Dokumente
Introduction to C
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 1
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions memory types using special processor features writing interrupt service routines including assembly language statements
Overview
Embedding Ideas
Knowledge of the processor instruction set is not required Details like register allocation and addressing of memory and data is managed by the compiler Programs get a formal structure and can be divided into separate functions
Programming and program test time is drastically reduced, this increases efficiency
Keywords and operational functions can be used that come closer to how humans think The supplied and supported C libraries contain many standard routines such as numeric conversions Reusable code: Existing program parts can be more easily included into new programs, because of the comfortable modular program construction techniques The C language based on the ANSI standard is very portable. Existing programs can be quickly adapted to other processors as needed.
3
Embedding Ideas
The growing popularity of C and the changes over the years by compiler creators not involved in the original design started to lead to several C derivatives
In 1983, the American National Standards Institute (ANSI) established a committee whose goal was to produce an unambiguous and machineindependent definition of the language C
The result is the ANSI standard for C
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions memory types using special processor features writing interrupt service routines including assembly language statements
Embedding Ideas
Embedding Ideas
The compiler automatically adds startup code to initialize the underlying processor The linker adds library code as used within the source code as needed
The program source code consists of Modules (source files) Variables store the calculation values float Voltage; int Temperature; Statements are the programming instructions Voltage = 0; Temperature = Temperature - 273; Functions are sequences of statements float CalculateCurrent(float Voltage) { return Voltage / 470; }
Embedding Ideas
Embedding Ideas
Keywords
The following keywords are reserved and may not be used otherwise
Embedding Ideas
char double enum float int long short signed struct union unsigned void typedef variable type declarations const auto extern register static volatile variable type modifiers for do while continue break - loops if else switch case default break conditional execution
Embedding Ideas
11
Operators
C defines a lot of operators Assignment
= MyVar = 5; Assignment // assign five to variable MyVar
Embedding Ideas
Relational operators
<, <=, >=, >
Less than, less than or equal to, greater than or equal to, greater than MyVar2 = MyVar >= 5; // if MyVar is greater than or equal to five // the result is one (TRUE), otherwise zero (FALSE)
12
Arithmetic operators
Embedding Ideas +, -, *, / Add, subtract, multiply, divide MyVar2 = MyVar + 5; // add five to MyVar, assign // result to MyVar2 % Modulo MyVar2 = MyVar % 5; // if MyVar is 13 the result is 3 ++, -MyVar++; Increment, decrement // MyVar is incremented by one
|, &, ^, ~ Bit wise OR, AND, exclusive or and NOT MyVar2 = MyVar & 0x0F; // if MyVar is 0x12 // the result is 0x12 AND 0x0F = 0x02 >>, << Bit wise shift right and left MyVar2 = MyVar << 3; // if MyVar is 0x12 (00010010 binary) // the result is 0x90 (10010000 binary)
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 13
Boolean operators
! MyVar2 = ! MyVar; Boolean NOT // if MyVar is 0x12 (00010010 bin) // the result is 0xED (11101101 binary) Embedding Ideas
==, != Equal to, not equal to MyVar2 = MyVar == 5; // if MyVar is five, the result is one (TRUE) //otherwise zero (FALSE) &&, || Boolean AND and OR
MyVar2 = (MyVar > 5) && (MyVar < 9); // if MyVar is greater than five AND less //than nine which means it is between five //and nine, the result is one (TRUE) //otherwise zero (FALSE)
14
Pointer operators
., -> Element access, pointer to element MyVar2 = MyStruct.MyElem; // Access the element named MyElem of the // structure MyStruct MyVar2 = pMyStruct->MyElem; // Access the the element named MyElem of the // structure pointed to by pointer pMyStruct & Address-of operator pMyStruct = &MyStruct; // Assigns to pointer pMyStruct the address of // structure MyStruct * Dereferencing operator (do not confuse with multiply) Embedding Ideas
15
Increment and decrement expressions can be written in compressed forms using increment and decrement operators Incrementing X as in X = X + 1; can be written as X++; Decrementing X as in X = X - 1; can be written as X--;
Embedding Ideas
The unusual aspect is that ++ and - - may be used either as as prefix or postfix operators Prefix operator before the variable ++X Postfix operator after the variable X++ In both cases, the effect is to increment X The expression ++X increments X before its value is used, while X++ increments after its value has been used Depending on the context, where the value is being used, the result is different Assume X is 5, then Z = X++; sets Z to 5, but Z = ++X; sets Z to 6. In both cases, X becomes 6.
16
Assignment Operators
Embedding Ideas
Expressions can be written in compressed forms Expressions in which the left hand side variable is repeated immediately on the right side as in X = X + 2; can be written as X += 2;
Combined operators like this are called assignment operators and most binary operators have a corresponding assignment operator
+=, - =, *=, /=, %= ^=, |=, <<=, >>=
17
Constants
Embedding Ideas
Decimal, octal, hexadecimal character and string constants are supported 16 decimal integer (starts with non-zero digit) 075 octal integer (starts with zero digit) 0xFABB hexadecimal values (starts with 0x) 61.0 floating point number (decimal point) 61e1 floating point number (exponential part) 'a' the character a '\r' the control character carriage return '\n' the control character line feed "abc" a string of characters the string is stored as an array of characters a NULL character is added automatically so the string occupies four bytes in memory
18
Embedding Ideas
19
Program Syntax
Embedding Ideas The program syntax is the rule how the source code is to be written to be translated by the compiler Basic syntax elements are Source comments are preceded with a double slash // int X; // comment
For multiple line comments the /* and */ pair can be used /* comment comment comment */
int X;
/* comment */
20
Embedding Ideas
Function arguments are surrounded with parentheses ( ) int func(int Param) // function declaration { } Result = func(X); // function call
21
Embedding Ideas
Arrays are defined by brackets [ ] int X[10]; // array declaration statement X[4] = 5; // assignment to array element
22
Embedding Ideas
23
Data Types
Embedding Ideas
The following basic data types are defined to be used for program variables and function arguments Data Type signed char unsigned char signed int unsigned int signed long unsigned long float double pointer Size Range of values 1 Byte -128 to +127 1 Byte 0 to 255 (i.e. a BYTE) 2 Byte -32768 to +32767 2 Byte 0 to 65535 (i.e. a WORD) 4 Byte -2147483648 to +2147483647 4 Byte 0 to 4294967295 (i.e. DWORD) 4 Byte 1,176E-38 to 3,40E+38 8 Byte 1,7E-308 to 1,7E+308 1, 2 or 3 Bytes, as address of objects (depending of memory type)
24
By default the basic data types char, int and long Embedding Ideas are signed, so the declaration
long Var;
is equal to
signed long Var; For some compilers, char is unsigned by default The ANSI norm states that char should hold one character of the targets character set Be aware of UNICODE character sets using 16 bit chars For 32 Bit target processors, the data type int is 32 bits by default The ANSI norm states that int should be the same size as the processors registers The programmer has to use short int to get a 16 bit value
25
Type Casting
If possible the compiler does implicit type casting Embedding Ideas int Val16bit; // short integer (16 bits) long Val32bit; // long integer (32 bits) Val32bit = Val16bit; // implicit type casting The compiler does no unsafe type casting as from a 32 bit value (long) to a 16 bit value (int) To convert from long to int the programmer has to manually type cast the value To do type casting, the value to cast has to be preceded by the target type enclosed in parantheses int Val16bit; long Val32bit; Val16bit = (int) Val32bit; // short integer (16 bits) // long integer (32 bits) // type casting // the higher 16 bits are lost Information may be lost by type casting The range of a value should be checked before doing manual type casting
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 26
Variable Declaration
Embedding Ideas All variables must be declared by type and name int Var; // declares a integer variable named Var C is a hardware oriented language this feature is expressed by the fact that it is possible for the programmer to declare the storage class of a variable auto variable stored on the stack static variable stored in static memory register variable should be stored in a processor register The storage class is optional if not specified the compiler uses a default storage class. Variable declaration is valid for the current scope (discussed later) The default storage class int Var; // use the auto storage class
Explicit storage classes int Var1; auto int Var1; register int Var1; static int Var1;
27
Arrays
Embedding Ideas
Arrays are defined by supporting the count of elements enclosed in brackets after the declaration int data[10]; //Defines an array of ten integers
By definition the name of the array without an index in brackets returns the starting address of the array in memory which is the same as the address of the first element pDataArray = data; // the address of the array pDataArray = &data[0]; // is equal to the address of // the the first element Note: There is no need of the address-of operator in the first line
28
Array subscripts always start at zero so the elements are data[0], data[1], , data[9] The last element has the index value of 9 and not 10 as in the declaration!
Embedding Ideas
In memory the first element (index zero) is stored in the lowest address immediately followed by the succeeding elements To get the element count of an array, divide the total size by the size of the first element // declaration of a string (array of chars) char Str[] = Hello; int CharCount = sizeof(Str) / sizeof(Str[0]);
29
For convenience, you can define a countof macro Embedding Ideas returning the element count of an array
// macro returning the element count of an array
30
Structures
Embedding Ideas Structures are grouped data elements Unlike arrays, the elements dont have to be of the same type The data type composition must be made known to the compiler by a structure definition struct sPerson { char Name[10]; int Age; float Weight; The newly defined structure named sPerson is composed of the ten bytes character string Name, the integer Age and the float value Weight Note: this is simply a definition, there has not yet been any memory allocated or variable of this type declared
31
Declaring a variable of the new structs type struct Embedding Ideas As a standard variable declaration, the type is struct sPerson A structure may be initialized struct The initialization values for all structure elements has to be given enclosed in braces
Once declared, the elements of the structure can be accessed through the name of the structure variable followed by the dot operator . and the name of the desired element
32
The output of this call would be the weight of Tom (42 years old) is 83.2
Embedding Ideas
33
Unions
Embedding Ideas Unions are grouped data elements of the different type Unlike structures, unions contain only one selected element at a given time A union is always big enough to hold the biggest element union uPerson { char Name[10]; int Age; float Weight; } employee; Note that all members of the union use the same memory location the programmer has to care about the current type of the content employee.Age = 44; // union holds age employee.Weight = 77.7; // union now holds weight if(employee.Age > 40) // invalid usage of union
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 34
Embedding Ideas
35
Functions
Embedding Ideas qFunction declaration A function is declared by its type and name followed by an argument list enclosed in parentheses ( ) The parentheses are mandatory even if the function has no arguments in this case the argument list is empty The statements of the function are enclosed in braces { } following the declaration The function uses the return keyword to return a result value to the caller Example of a function with no parameters returning an integer result int FunctionName( ) { return 5; }
36
Calling a function
Embedding Ideas
A function is called by naming it, followed by a parenthesized list of arguments A function may return a result value which can be assigned to other variables Examples FunctionName( ); Result = FunctionName( );
37
38
Embedding Ideas
39
Strings
Embedding Ideas C does not provide a fundamental string data type Strings are represented as arrays of characters with a terminating zero character (also called ASCIIZ strings) To manipulate strings, the user has to use library functions strlen returns the length of a string (the number of characters) strcpy copy one string into an other strcat concatenate two strings strcmp compare two strings strchr Attention ! There is no compiler or runtime check for enough space in a character array string functions may accidentally overwrite the data following the array Dont forget to count the tailing zero character
40
Statements
Embedding Ideas
Expression statements are valid C expressions followed by a semicolon Arithmetic expressions a = 5; Function calls func(12); The empty statement (a single semicolon) ; A block of statements that logically belong together and that we want to be treated as a unit can be grouped together using braces
41
Embedding Ideas
A block or compound statement is from the syntax point of view equivalent to a single statement Blocks may be nested Variables or any other declarations have a scope within the program the scope defines the region within a program in which the variable is active (or known) Declarations are active in the block they are defined in Enclosed blocks inherit all declarations from its parent if no new declaration overwrites the declaration
42
Have a look at nested blocks and the activity of Embedding Ideas declarations { int A; // declaration of A active { int B; // declaration of A and declaration of B active { int A; // second declaration of A overwriting previous int C; // second declaration of A and declaration of c active } // activity of second declaration of A ends here // first declaration of A and declaration of B active } // activity of declaration of B ends here // only first declaration of A active }
43
Embedding Ideas
44
Embedding Ideas
Conditional execution using the if and else statements Conditional expressions with the ternary operator ? : Conditional execution using switch and case if (a > b) // checks the expression a > b z = a; // statement executed if expression is true else z = b; // statement executed if expression is false
45
Conditional Expressions
Embedding Ideas The conditional expression, written with the ternary operator ? :, provides an alternate way to write the following and similar constructions (expression1) ? expression2 : expression3 First a condition expression1 is evaluated Depending of the result one of two other expressions is evaluated and that is the value If condition expression1 is true (non-zero) expression2 is evaluated If condition expression1 is false (zero) expression3 is evaluated z = (a > b) ? a : b; // z = max(a, b)
46
Conditional Execution
Embedding Ideas
47
Using the switch, case and break statements, an expression can be be tested to match a number Embedding Ideas of constant integer values the default case catches all other values
switch(d) { case 1: printf("Mon"); // executed for d is one break; case 2: printf("Tue"); // executed for d is two break; default: // executed if d does not match // one of the case values printf("<invalid>"); }
48
Embedding Ideas
Case values are constants of type integer All case values must be different The case labeled default is executed if none of the other cases are satisfied The default label is optional If it isnt there and none of the cases match, no action at all takes place Cases and default can occur in any order The break statement to immediate exit from the switch Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape
49
Embedding Ideas
50
Embedding Ideas
51
Loops using do in contrast to loops using while Embedding Ideas first execute a statement or block of statements and then test the given expression
52
To execute a statement or block of statements for a number of times, the for statement provides a generalized form of the while functionality
Embedding Ideas
Within the parentheses there are three parts separated by semicolons The first part is the initialization and is done once before the loop is entered The second part is the test condition that controls the loop this condition is evaluated and if true, the body of the loop is executed Then the third part is executed and the condition is re-evaluated for(c = 1; c <= 8; c++) printf("%d ", c); // will print out 1 2 3 4 5 6 7 8
53
Jump Statements
Embedding Ideas The principle of structured programming technique is A block should have only one entry A block should have only one exit The break statement can be used to force an immediate exit from while, do, and for loops It is sometimes convenient to be able to exit from a loop other than by testing at the top or bottom break causes the innermost enclosing loop to be exited immediately The continue statement causes the next iteration of the enclosing while, do, and for loop to begin In the while and do, this means that the test part is executed immediately In the for, control passes to the third part
54
Embedding Ideas
goto err; // jump directly to label err err: // define label err
Formally goto is never necessary In practice it is almost always easy to write code without it The most common usage is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once
55
Pointers
Embedding Ideas A pointer to a variable essentially is the address of it While the variable declaration is int A; // integer variable named A In memory the variable occupies a piece of data space Memory space used by declaration of the content of this memory is undefined until a value is assigned to the variable. The declaration of a variable that points to an integer is int* pA; // variable pA is a pointer to an int
Because the pointer variable is a variable too, it also occupies a piece of data space. Memory space used by pointer variable pA the content is also undefined.
56
Pointer can be initialized by assigning it an address of a Embedding Ideas variable of the corresponding type using the address-of operator & pA = &A; // variable pA points the variable A
The value of pointer variable pA is initialized with the address of variable A the address is stored into the memory space reserved for the pointer at its declaration. The memory of the variable A the pointer points to is still undefined !
57
Now A can be indirectly accessed through the pointer using the dereferencing operator * *pA = 5; // set variable A to 5
Embedding Ideas
Indirectly assigning a value to variable A, the value of pointer variable pA (i.e. the address of variable A) is used to store the value into the memory space reserved for the variable A at its declaration. Now all of the memory spaced reserved by the declarations contains valid data.
58
Rules valid for pointers pointers are typed they point to a specific type Special untyped pointers are declared by void* Pointer arithmetic takes care of the pointer type adding one to an pointer to long will result in the address of the next long in memory
Embedding Ideas
long L; // declare long variable long* pL = &L; // pL points the variable L pL++; // pL holds the memory address of // the first byte after L
59
Pointer usage Use pointers to return more than one result from a function (parameter passing by reference) void swap(int* pA, int* pB) // by reference { int temp = *pA; *pA = *pB; *pB = temp;
Embedding Ideas
Because array elements are stored sequentially in memory, pointers can be used to access array elements
int Ar[100]; // array of ints int* pAr = &Ar; // pAr points to the first element pAr++; // pAr points to the second element pAr += 3; // pAr points to the fifth element
60
pointers, references, dereferencing, addressof, Embedding Ideas Pointer declarations may be nested to build pointers to pointers int A; // an int variable A int* pA; // pA points to an int int** ppA; // ppA points to a pointer to an int ppA = &pA; // initialize ppA to a point to pA The dereferencing operator can be used to access the value pointed to *ppA = &A; // this initializes pA to point to A **ppA = 69; // sets A to 69
61
Pointer Tips
Embedding Ideas Use lower case p in front of pointer names to reflect the pointer type in the name this notation is more readable To see what *ppA means and what type it is simply match the expression with the declaration int** ppA; // declaration (pointer to pointer to int) // so *ppA is what ? int** ppA // simply cover what is given // the remaining text is the type information // you are looking for // thus *ppA is a pointer to an int
// so **ppA is what ? int** ppA // again cover what is given // **ppA is an int so you can assign a value **ppA = 5;
62
The conversion from an array to a pointer can also be done at run time // declaration of a string (array of chars) char StringArray[] = Hello; // declaration of a string pointer char* StringPointer; // initalization of string pointer // with address of array StringPointer = StringArray;
Embedding Ideas
Accessing an arrays values can be done by two methods Using an index // accessing array elements by index int i; for(i = 0; i < 5; i++) putc(StringArray[i]);
63
Using an element pointer // accessing array elements by element pointer int i; // initialize pointer to point to first element char* pElement = StringArray; for(i = 0; i < 5; i++) putc(*pElement++);
Embedding Ideas
This is an example of C being somewhat inconsistent; this *pElement++ statement does not mean "increment the thing being pointed at" but rather, increment the pointer itself, so causing it to point at the next sequential address. Thus in the example the character is obtained and then the pointer moved along to point at the next higher address in memory.
64
65
Create An Array In The Form Of A String unsigned char string_arr[] = "HELLO"; Create A Pointer To A String unsigned char* string_ptr = "HELLO";
Embedding Ideas
66
Embedding Ideas
67
68
Embedding Ideas
69
70
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions memory types using special processor features writing interrupt service routines including assembly language statements
71
Embedding Ideas
The compiler preprocesses the source code to provide some facilities this is conceptually a separate first step of compilation #include is used to include the contents of another source file #include reg51.h; // include register definition // header file at this place in the source code #include <reg51.h>; // same, but look in include // file directory instead of current directory
72
#define MAXCOUNT 5 // replaces all occurrences of // MAXCOUNT in the source by five Macros may optionally have parameters
Embedding Ideas
#define MIN(a,b) ((a<b) ? a : b) // the macro is expanded to the source code // this can be used instead of inline functions #if, #else and #endif provides a way to include code sequences selectively, depending on the value of conditions evaluated during compilation #if VERSION < 5 // condition // this code is compiled if condition is true #else // this code is compiled if condition is false #endif it is mostly used to generate version or target hardware dependent code
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 73
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions memory types using special processor features writing interrupt service routines including assembly language statements
74
Libraries
Supplied with the compiler are several standard C libraries (defined by the ANSI standard) Embedding Ideas
stdio standardized input and output (keep in mind that there is no console in an embedded system) string functions to manipulate strings stored in character arrays math mathematical functions like sin, cos, exp, log, mod, stdlib number conversion and storage allocation functions (keep in mind that there may be no dynamic memory) signal functions providing facilities for handling exceptions
75
Embedding Ideas You may decide to write your own libraries to hide source code portions to other developers Driver libraries containing functions to access a special hardware feature of your hardware (for example a display or keyboard driver) Commonly used calculation routines Use libraries to divide development tasks between several programmers
76
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions memory types using special processor features writing interrupt service routines including assembly language statements
77
C Language Derivatives
Embedding Ideas
C++ C++ is a object-oriented extension to the language Code can be mixed between C and C++ C++ needs a dynamic memory manager which is why it is rarely used in embedded environments where memory is a rare and expensive resource
Embedded C++ Embedded C++ (also called EC++) is a special implementation of C++ witch takes care of the needs of embedded systems The full C++ features are limited to meet these needs
78
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions: data types language extensions: memory types using special processor features writing interrupt service routines including assembly language statements
79
The use of these new data types is exactly the same as for basic data types bit MyBitValue; MyBitValue = 1; // declare a bit variable // assign a value
For the access to variables defined as these types the compiler uses fundamental assembly language statements -This optimizes the resulting code size -This maximizes the execution speed
80
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions: data types language extensions: memory types using special processor features writing interrupt service routines including assembly language statements
81
-code Code area of the program (i.e. read only) -data Directly addressable internal memory -idata Indirectly addressable internal memory -xdata Chip external data -bdata Area with individually addressable data bits
Attention ! Keep in mind that these extensions are processor specific and may not be portable
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 82
83
It is also possible to locate the executable code of a function using the at keyword at 0x8000 void AbsoluteFunction() { }
Embedding Ideas
One possible use of this is to locate precompiled code in separate memory (ROM) and access this code from outside
84
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions: data types language extensions: memory types using special processor features writing interrupt service routines including assembly language statements
85
Embedding Access to processor specific registers (SFRs) allows to Ideas use the chip internal peripherals
The compiler handles this type of variable in special ways: A sfr variable cannot be of a compound type (array, struct or union)
struct { int Element1; at 0xE0 sfr ACC; };
// impossible declaration
at 0xE0 sfr ACC; // declaration unsigned char pAcc; pAcc = &ACC; // invalid use of the operator
86
Embedding Ideas
at 0xE0 sfr ACC = 0x55; // impossible The sfr declaration must be given an absolute storage class attribute, which includes the at instruction and register address sfr ACC; // missing absolute storage address Only int and char qualifiers are permitted (i.e. long, float, signed, etc. are not allowed) at 0xE0 sfr float ACC; // invalid sfr data type
87
The compiler assumes that the value of the variable may be changed externally (i.e. by the processor) at 0x8B sfr TL1; // declaration unsigned char Value; Value = TL1; // get value of SFR TL1 Value = TL1; // the compiler assumes // that the value of SFR ACC may be changed // between the two statements // otherwise code optimization will remove // the second assignment
Embedding Ideas
88
Memory Types
Embedding Ideas The availability of internal and external memory and its size depends on the embedded systems scale
Internal memory (also called on chip memory) Embedded processors supports internal memory used for RAM for data storage RAM for the call stack ROM for program storage (FLASH or factory mask programmed)
External memory (not available in all embedded environments) RAM for data storage RAM for the call stack (dependent on memory model) ROM for program storage of large programs (ROM, FLASH or EPROM)
89
Perhaps the initially most confusing thing about Embedding Ideas the 8051 is that there are three different memory spaces, all of which start at the same address. Other microcontrollers have a single Von Neuman memory configuration, where memory areas are located at sequential addresses; regardless of in what device they physically exist. Memory models are used to define The default memory type to be used for local variables and other declarations without an explicit memory type The stack location Available Models are TINY, SMALL, MEDIUM, COMPACT, LARGE and HUGE
90
TINY Total RAM 128 bytes and small code Embedding Ideas (up to 2k) TINY is identical to the SMALL memory model, except that ACALL and AJMP instructions are generated rather than LCALL and LJMP. This limits the code size to 2K bytes and is useful for those devices that do not support the LCALL and LJMP instructions However when considering memory spaces the TINY and SMALL memory models are identical.
SMALL Total RAM 128 bytes Using this memory model, the number of global variables must be kept to a minimum to allow the linker's OVERLAY function to work to best effect. With 8052/32 versions, the manual use of the 128 byte IDATA area above 80H can allow applications additional variable storage space, however the amount of space required for the stack must be kept in mind.
91
The SMALL model can support very large programs by manually forcing large and/or slow data objects in to an external RAM, if fitted. Also variables that need to be viewed in real time are best located here, as dual-ported emulators (like the ones from Hitex and Raisonance) can read their values on the fly. This approach is generally best for large, time-critical applications, as the SMALL global model guarantees that local variables and function parameters will have the fastest access, while large arrays can be located off-chip.
Embedding Ideas
92
COMPACT Total RAM 256 bytes off-chip, 128 or 256 bytes on-chip Suitable for programs where, for example, the on-chip Embedding Ideas memory is applied to an operating system. The compact model is rarely used for an entire program, but more usual in combination with the SMALL switch reserved for interrupt routines. Especially useful for programs with a large number of medium speed 8 bit variables, for which the MOVX A,@R0 is very suitable. It can be useful in applications where stack usage is very high, meaning that data needs to be off-chip. Note that register variables are still used, so the loss of speed will not be significant in situations where only a small number of local variables and/or passed parameters are used. LARGE Total RAM up to 64KB, 128 or 256 bytes on-chip Permits slow access to a very large memory space and is perhaps the easiest model to use. Again, not often used for an entire program, but in combination with SMALL. As with COMPACT, register variables are still used and so efficiency remains reasonable.
93
In summary, there are five memory spaces available for data storage, each of which has particular pros and cons.
Embedding Ideas
DATA 128 bytes; SMALL model default location Best For: Frequently accessed data requiring the fastest access. Interrupt routines whose run time is critical should use DATA. Worst For: Variable arrays / structures that contain more than a few bytes. IDATA 128 bytes or 256 bytes; Not model-dependant Best For: Fast access to data arrays and structures of limited size (up to ~ 32 bytes each) but not totalling more than 64 or so bytes. Worst For: Large data arrays and/or fast access words. CODE 64K bytes Best For: Constants and large lookup tables, plus opcodes, of course! Worst For: Variables! It's ROM that can not be written to. PDATA 256 bytes; COMPACT model default area Best For: Medium speed interrupt and fast background char (8 bit) variables and moderate-sized arrays and structures Worst For: Very large data arrays and structure above 256 bytes. Very frequently used data (in interrupts etc..). XDATA up to 64K bytes; LARGE model default area Best For: Large variable arrays and structures (over 256 bytes) Worst For: Frequently-accessed or fast interrupt variables.
94
HUGE Additionally the stack is stored in external memory Embedding Ideas The call and parameter stack is placed in external RAM. Permits slow access to the stack and should only be used if no other model fits. Choose the memory models from the complexity of your application and the hardware available The compiler selects the appropriate instructions depending of the memory model -Depending on the code size the compiler may use short jumps instead of long jumps -This saves code space and speeds up execution Some memory model features may be mixed -To meet special requirements even with a small model external connected device can be accessed by explicit xdata declaration
95
Embedding Ideas
The compiler has to save the active register banks state on function calls
To overcome this overhead functions can be defined to use a special register bank by assigning the using keyword The compiler inserts code to select the given register bank at the beginning of the function This feature is often used in combination with the interrupt attribute to speed up interrupt handling (no registers have to be saved to and restored from the stack) void fct1 (void) using 1 { // function code using register bank 1 }
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 96
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions: data types language extensions: memory types using special processor features writing interrupt service routines including assembly language statements
97
Embedding Ideas To use on-chip peripherals the user often has to write interrupt driven routines so called interrupt handlers Interrupt handlers are called on hardware demands The entire processor state (i.e. the registers) has to be saved on procedure entry and restored on exit Use the interrupt keyword to identify a function as interrupt handler
The compiler automatically provides specific code for interrupt handler routines The compiler automatically provides a interrupt vector jump to the routine At the start of the function the register set is saved and restored at return To exit, the RETI instruction is used in place of RET
98
A step by step example to implement a timer 2 interrupt service routine for a 8051 derivate 87C591 Embedding Ideas Implement a 50ms tick interrupt handler Count up a global variable g_counter Steps to implement the interrupt service routine Read the processors reference manual to Add initialization code for the device Add code to enable the interrupt Get the interrupt number for the device and implement a function handling the interrupt
99
Embedding Ideas Writing Interrupt Service Routines step 1/1 The necessary device initialization (see TM2CON)
Writing Interrupt Service Routines step 1/2 Calculate the 16-bit reload value for the timer Use the Microcontroller Peripheral Timing Calculators provided by the Embedded Systems Academy to calculate the necessary register values Enter the clock frequency and desired timer run-time Hit the Calculate button to execute the calculations
100
Writing Interrupt Service Routines step 1/3 Add initialization code for the timer
Embedding Ideas
Load the timer registers with the reload value provided by the Microcontroller Peripheral Timing Calculator
TMH2 = (15536 >> 8); TML2 = 15536 & 0xFF; Set the timer mode TM2CON = 0x85; // 1/6 x fCLK clock source, // clock source and // 16-bit overflow interrupt select // load MSB // load LSB
101
Writing Interrupt Service Routines step 2/1 How to enable the interrupt See the documentation for SFR IEN0
Embedding Ideas
Writing Interrupt Service Routines step 2/2 The two steps to enable the timer 2 interrupt
Set the Timer 2 overflow interrupt select This is already done by setting T2IS1 in SFR TM2CON while initializing the timer mode Set the general interrupt enable bit (EA) EA = 1; // generally enable interrupts
102
Writing Interrupt Service Routines step 3/1 Get the interrupt number In the documentation look at interrupt vectors
Embedding Ideas
Writing Interrupt Service Routines step 3/2 How to reset a pending interrupt The processor signals the timer 2 overflow by setting the bit T2OV in the TM2IR register At the same time the interrupt handler is activated To reset the pending overflow the programmer has to clear the overflow bit Writing Interrupt Service Routines step 3/3 Implement a function handling the interrupt Write a function without parameters and without a return value Use the interrupt keyword with the interrupt vector found in the documentation Add the code to reset the pending interrupt in the hardware void fct_timer2 (void) interrupt 14 { g_counter++; T2OV = 0; // reset pending interrupt }
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 103
To overcome stack limitations in embedded processors there are different parameter passing conventions Parameters are passed in special registers (The register allocation is compiler specific) If there are more parameters than register space the remaining parameters are passed on the stack Passing parameters in registers the functions cant be called recursively Some compilers allow explicit setting the calling convention to implement recursive functions #pragma REGPARMS #pragma NOREGPARMS To write assembly subroutines the knowledge of the parameter passing conventions are essential
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 104
105
Objective
Introduction to the C language overview elements of C language compiler preprocessor libraries C language derivatives
Embedding Ideas
Using C in an Embedded Environment language extensions: data types language extensions: memory types using special processor features writing interrupt service routines including assembly language statements
106
Embedding Ideas
Embedded applications sometimes requires to implement code sequences in assembly language To ensure a predefined timing To have highly hand-optimized routines #pragma asm SETB P3.0 NOP NOP NOP CLR P3.0 #pragma endasm
107