Sie sind auf Seite 1von 107

Embedding Ideas

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

Overview

Advantages over assembly language programming

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

The ANSI standard

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

The structure of a program


All C programs consists of at least - A main module (a source file) - The main function

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

goto return program flow control


sizeof type information
TICO INSTITUTE OF EMBEDDED TECHNOLOGY 10

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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)

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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)

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

MyVar2 = *pMyInt; // Access the value pointer pMyInt points to


TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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.

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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
+=, - =, *=, /=, %= ^=, |=, <<=, >>=

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

18

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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 */

older compilers only support the second type of comments

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

20

Basic syntax elements (continued)


Statements are terminated with a semicolon ; int X; // declaration statement X = 5; // assignment statement

Embedding Ideas

Function arguments are surrounded with parentheses ( ) int func(int Param) // function declaration { } Result = func(X); // function call

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

21

Basic syntax elements (continued)


Statement blocks are enclosed in braces { } if(X > 5) { // start of block X = 5; // statements func(X); } // end of block

Embedding Ideas

Arrays are defined by brackets [ ] int X[10]; // array declaration statement X[4] = 5; // assignment to array element

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

22

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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)

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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;

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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]);

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

#define countof(arr) (sizeof(arr) / sizeof(arr[0]))


// now the above code looks like this int CharCount = countof(Str);

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

employee.Age = 42; // set structure element age


printf(the weight of %s (%d years old) is %f\n, employee.Name, employee.Age, employee.Weight);

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

32

The output of this call would be the weight of Tom (42 years old) is 83.2

Embedding Ideas

Followed by a carriage return and line feed pair (\n

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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; }

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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( );

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

37

The void Keyword


Embedding Ideas The void keyword is used to explicitly state no value it is used in several declarations Functions (parameters) int FunctionName(void) means that the function does not have any parameters Functions (return value) void FunctionName(int Param) means that the function does not return a result Pointers void* pNothing means that the pointer does not point to a specific data type or the data type is not known at this point

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

38

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

{ a = 5; func(12); } // no semicolon here !

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

41

Blocks And Scope

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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 }

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

43

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

44

Conditional Execution / Expressions


The C language provides alternate ways to write conditional statements

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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)

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

46

Conditional Execution

Embedding Ideas

Nested if-else statements can be used to implement a multi-way decision


if(d == 1) printf("Mon"); else if(d == 2) printf("Tue"); else if(d == 3) printf(Wed"); else if(d == 4) else printf("<invalid>"); // executed for d is one // executed for d is two // executed for d is three

// executed if d does not match // one of the above values

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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>"); }

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

48

Rules valid for switch statements

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

49

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

50

Flow Control Statements


Flow control statements are Loop statements -for -do -while Jump statements -break -continue -goto -return

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

int c = 0; do printf("%d\n", ++c); while(c < 8); // will print out 1 2 3 4 5 6 7


Differences between loops using do and while while(expr) first test then action do while(expr) first action then test

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

Endless loops can be written as for( ; ; )

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

54

C provides the infinitely-abusable goto statement and labels to branch to

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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.

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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 !

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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.

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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;

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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]);

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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.

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

64

Summary Of Arrays And Pointers


Create An Uncommitted Pointer unsigned char* x_ptr; Create A Pointer To A Normal C Variable unsigned char x; unsigned char* x_ptr = &x; Create An Array With No Initial Values unsigned char x_arr[10]; Create An Array With Initialized Values Embedding Ideas

unsigned char x_arr[] = { 0, 1, 2, 3 };

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

Create A Pointer To An Array


unsigned char string_arr[] = "HELLO"; unsigned char* string_ptr = string_arr; Force A Pointer To Point At The Next Location string_ptr++;

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

66

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

67

The first C program


Embedding Ideas This most popular first C program #include <stdio.h> // includes source lines containing // information about standard library main() // define a function named main { // that receives no argument values printf("hello world"); // call the library function printf } // to print this sequence of characters The program editor included in the programming environment supports syntax highlighting Attention ! The result of the library function printf is not standardized for embedded environments consult the documentation.

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

68

Elements of C Language: Contents


The Structure of a program Keywords Operators Program Syntax Data Types and Type Casting Functions Declaring a function Calling a function String handling in C Conditional expressions Flow control statements The first C program Including assembly language statements

Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

69

Include Assembly Language Statements


Embedding Ideas Use the asm keyword to include simple opcodes into the code asm {0x02,&fct_error}; // ljmp to fct_error (You have to know the hexadecimal value of the opcode) The second me method is to include assembly mnemonics #pragma asm and #pragma endasm are used to identify a block of mnemonics #pragma asm LJMP fct_error #pragma endasm Attention ! Keep in mind that assembly language statements are not portable to other processors The asm keyword and the asm pragmas are not part of the ANSI standard

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

71

The Compiler Preprocessor

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

#define replaces a token by an arbitrary sequence of characters (also called a macro)

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

79

Language Extensions: Data Types


New data types Embedded C compilers define special data types for use with the specific target processor -bit One bit (processors that support bit operations) -sfr Special function register -sbit, sfrbit One bit of a special function register Embedding Ideas

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

81

Language Extensions: Memory Types


There might be several memory areas available inside and outside the embedded system processor Size and availability varies between systems New space qualifiers To access the different memory types of the processor, the compiler adds additional keywords to specify this Embedding Ideas

-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

Locating Variables To Absolute Addresses


Sometimes it becomes necessary to place variables or constants to fixed locations in an embedded system Access components connected to the external bus Access special regions of memory Meet processor needs for special memory regions Absolute location is done with the at keyword Set the location of single data bytes at 0x20 data char my_byte; Set the location of a complete structure to access the registers of an external device typedef struct { unsigned lcr,dll,dlm,lsr,iir,ier,mcr,msr,rbr,thr; } UART8250; xdata at 0xfe00 UART8250 COM1; Embedding Ideas

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

85

Using Special Processor Features

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

The address-of operator can not be applied

at 0xE0 sfr ACC; // declaration unsigned char pAcc; pAcc = &ACC; // invalid use of the operator

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

86

A sfr variable cannot be initialized

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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)

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

89

Memory Models - Introduction

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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.

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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.

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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.

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

95

Using Special Register Sets


Processors support more than one register bank

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

97

Writing Interrupt Service Routines

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

Passing Parameters To Functions


Standard C defines that parameters are passed on the stack Embedding Ideas

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

Returning Result Values


Embedding Ideas Standard C does not define a standard to return values from a function Most compilers return the value in the processor registers Depending on the size of the value to return the compiler selects between different value returning methods A register (by default the accumulator) A set of registers A previously reserved space on the stack To write assembly subroutines the knowledge of the value returning convention is essential

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

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

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

106

Including Assembly Language Statements

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

// ensure predefined // number of clock // cycles for // port signal

TICO INSTITUTE OF EMBEDDED TECHNOLOGY

107

Das könnte Ihnen auch gefallen