EMBEDDED PROGRAMMING IN C, C++ Objective he programming in an embedded environment -ui be performed using various levels of languages like assembly language, procedural languages and object oriented language. This unit aims at introducing the various programming concepts and the embedded implementation in those languages. The programming concepts will also include the memory optimization techniques and the source code engineering tools. 3.1 SOFTWARE PROGRAMMING IN ASSEMBLY LAI\IGUAGE (ALP) AIID IN IIIGH LBVEL LAITGUAGE'C' 3.1.1. Assembty Language Programming Assembly language lies in between the high level and low level languages. The assembly language uses mnemonic codes for writing the programs. Assembler is the tool which is used to convert the assembly language in the machine language. Advantages . It gives a precise contol of the processor internal devices and full use of processor specific features in its instruction set and its addressing modes. 3.2 Embedded The machine codes are compact. This is because the codes for declaring the conditions, rules, and data type do not exist. The system thus needs a smaller memory' Excess memory needed does not depend on the programmer data type selection and rule-declarations' It it ato not the compiler specific and library functions specific. Device driver codes may need .only a few assembly instructions. For example, consider a small ernbedded system, a timer device in a microwave oven or an automatic washing machine or an automatic chocolate vending machine. 3.1.2 tligh Level Language All the programming languages currently used are the high level languagls. The constructs of the programming language are gnifisf; fke structures. lnterpreter and the Compilers are the system progftms which are used to convert the high level language in the machine codes. Advantages The development cycle is short for complex systems l. Data lype declarations provide programming ease' 2. Type checking makes the program less prone to error' 3. Control structures and conditional Statements make the program-flow path design tasks siritple' 4. Portability of non-processor specific codes exists' Additional advantages of C as a high level languages It is a funguage between low (assembly) and high level tanguage. tnseiing the assembly language codes in- between is catta ln-line assembly. A direct hardware control is thus also feasible by in-line assembly, and the complex part of the program can be in high-level language. Propramming Concepts and Embedded Programming 3. 3 Summary High level language programming makes the program development cycle short, enables use of modular programming approach 'and lets us follow sound software engineering principles. 3,2 .C, PROGRAM ELEMENTS: HEADER AIID SOT]RCE FILES AND PREPROCESSOR DIRECTIVES: The 'C' program elements, header and source files and preprocessor directives are as follows: 3.2.1 Include Directive for the Inclusion of Files Any C program first includes the header and source files that are readily available Example # include semlib.h /* Include Semaphore functions Library */ Include is a peprocessor directive to include the contents (codes or data) of a file. Including Codes Files: These are the files for the codes already available. For example, #include "prctlHandlers.c". . Including Constant data Files: These are the files for the codes and may have the extension '.const'. . Including Stings data Files: These are the files for the ' strings and may have the extension '.strings' or'.str.' or '.txt. . Including initial data Files: There are files for the initial or default data for the shadow ROM of the embedded system. . Including basic variables Files:'These are the files for thq local or global static variables that are stored in the RAM because they do not posses the initial (default) values. 3.4 Embedded Systems . Including Header Files: It is a preprocessor directive, which includes the contents (codes or data) of a set of . source files. The pre-processor directives will be '# include (string.h>' and -' # inc lude Srnath.h>'. Also included are the header files for the codes in assembly, and for the VO operations (conio.h), for the OS functions and RTOS functions. The difference between inclusion of a header file, and a text file or data file or constants file is described as follows: l. The header files are well tested and debugged modules. 2. The header files provide access to standard libraries. 3. The header file can include several text file or C files. 4. A text file is description of the texts that contain specific information. 3.2.2 Source Files Source files are program files for the functions of application software. The source files need to be compiled. A source file will also possess the preprocessor directives of the application and have the first function from where the processing will start. This function is called main function. Its codes start with void main 0.The main calls other functions. 3.2.3 ConfigurationFiles Configuration files are the files for the configuration of the system. 3.2.4 PreprocessorDirectives . Preprocessor Global Variables: 'V define volatile boolean IntrEnable" is a preprocessor directive. It me,ans, it is a directive before processing to consider Pros:amming Concents and Embedded Prosrammins 3.5 IntrEnable a global variable of Boolean data type and is volatile. Preprocessor Constants: "# define false 0" is a prepiocessor directive. It means, it is a dircctive before processing to assume 'false' as 0. Summary o Preprocessor constants, variables and inclusion, of configuration files, text files, header files and library functions are used in C programs. o Functions are used when the requirement is that the code should be compiled once only. o A function may return nothing or a Boolean value or an integer or any primitive data type. 3.3 PROGRAM ELEMENTS 3.3.1 Macros A macro is a collection of codes that is defined in a program by a name. It differs from a function in the sense that once a macro is defined by a name, the compiler puts the corresponding codes for it at every place where that macro name appears Whenever the name of the macro appears, the compiler places the codes designed for it. Macros, called test macros or test vectors are also designed and used for debugging a system. How does a macro differ from a function? The codes for a function are compiled once only. On calling that function, the processor has to save the context, and on return restore the context. Macros are used for short codes only. This is because, if a function call is used instead of macro, the overheads (context saving and other actions on function call and return) will take a time. 3.6 Embedded 3.3.2 Functions The functions executes a named set of codes with values passed Uy, tt. calling program through its argumelts' Also returns a data ;ilj"; when It'is not declarei as voii, It has the context saving and retrieving overheads. Main Function Declarations of functions and data b/ps, typedef and either (i) Executes a named s"i or codes, calls a set of functions, and calls oiift" inttt-pts the ISRs or (ii) starts an OS Kernel' Interrupt senice Rodine or Daice Drtver Declarations of functi6ns and data Epes, one$et and Executes a named set of codes' Must bc short so that other sources of intemrpts arc also serviced within the deadlines' Must be either a reenfa'; routine or must have a solution to the shared data problem. Recurcive Function A function th4 calls itself. It must be a reefitrant function also' Most often ib use is avoi&d in embeddcd systems due to memory consmints. Reentiant Function Reentrant function is usable by the several tasks and routines synchronouslY. 3.3.3 ' Use of Data TYPes , . Whenev er adat ai s named, i t wi l l hav et headdr es s ( es ) allocated at the memory' The number of addresses allocated Jepends upon iht data type' 'C' allows the following Primitive data tYPes' . The char (8 bit) for characters, byte (8 bit)'^unsigned ttt"tt (16 ;it), strort (tO bit), unsigne{ lnt.OZ tit)' int (32 bit), il;i'oouutelo+ bil), float (32 bI) and double iOc Uit). tCJrtain compilers-do not take the 'byte' as a oata type'd"rinition, The ,char' ls then used instead of o I data type appropriate for the hardware is used' For example, u iO-iit'timer can have only the unsigned short data type, and its range can be from 0 to 65535 only. The tyi.Otf is also uJed' It is made clear by the following examPle' o { compiler version may no1 process the declaration as an unsigned byte' The ;unsigned character' can then be used as a Oata"typ"' It can then be declared as follows: 3.3.4 Use of Data Structures A data structure is an important element of any progtam' A few in,portun, data structur", ur. stack, one-dimensional array, queue, circular queue' plpe; u tuUtt (two dimensional amY)' lookup table, hash table and list' The following section gives the uses and shows exemplary uses of queues, stacks, alTays' lists and trees Queue ' It is a sfiucture with a series of elements with the first element *;ftg for an operation' An operation can be done only in thi first in first out (FIFO) mode' . lt is used when an element is not to be accessible by any index and pointer directly, but only through the FIFO' ' An element can be inserted only at the end in the series of elements waiting for an operation' , ' There are two pointers, one for deleting after the operation and other for inserting' Both increment after an oPeration. Example Print buffer. Each character is to be printed in FIFO mode' [yt.'. Vfott C compilers do not take a Boolean variable 3.8 Enlbedded Systems Stack . It is a structure with a series of elements with its last element waiting for an operation. An operation can be done only in the last in first out (LIFO) mode. . It is used when an element is not to be accessible by any index or pointer directly, but only through the LIFO. . An element can be pqshed (inserted) only at the top in the series of elements still waiting for an operation. . There is only one pointer used for pop (deleting) after the operation as well as for push (inserting). o Pointers increment or decrement after an operation. It depends on insertion or deletion. Example Pushing of variables on intemrpt or call to another function. Array (One Dimensional Vector) . It is a structure with a series of elements with each element accessible by an identifier name and an index. o Its element can be used and operated easily. It is used when each element of the sructure is to be given a distinct identity by an index for easy operation. Index stars from 0 and is fve integers. Example ts: 12 * l2ts[0] Total salary, ts is 12 times the first month salary. Multi-dimensional Array . It is a structure with a series of elements each having another sub-series of elements. . Each element is accessible by identifier name and trvo or more indices. . It is used when every element of the structure is to be given a distinct identity by two or more indices for easy operation. Proerammins Concepts and Embedded Programming 3.9 . The dimension of an array equals the number of indices that are needed to distinctly identiff an array-element. Indices start from 0 and are *ve integers Example Matrix or a pixel in an image frame. List . Each element has a pointer to its next element. . Only the first element is identifiable and it is done by list-top pointer (Header). No other 'element is identifiable and hence is not accessible directly. ' By going through the first element, and then consecutively through all the succeeding elements, an element can be read, or read and deleted, or can be added to a neighbouring element or replaced by another element. Example A series of tasks which are active, each task has pointer for the next task. Tree . It has two or more branches each having a daughter element. . Each daughter element has two or mone daughter elements. . The last one does not have daughters. . Only the root element is identifiable and it is done by the treetop pointer (Header). o No other element is identifiable and hence is not ' acressible dircctly. By traversing the root element, then proceeding continuously through all the succeeding daughters, a tree element can be read or read and deleted, or can be added to another daughter or replaced by another element. 3. 10 . Thel ast daught er , cal l ednodehasnof ur t her daught er s' l . A binary tree is a tree with a maximum of two daughters (branches) in each element' Example Anexampleisadirectory.Ithasnumberoffile.folders.Eachfile. folder has a numbtt oiott'tt file folders and so on' In the end is a file. I 3.3.5 Use of Modifiers The actions of modifiers are as follows: ' Modifier 'auto' or No modifier' if outside. a function I block, rnt-t- that there is ROM allocation for the vari abl euvtr' ' l o.uto' i fi ti si ni ti a| i zedi ntheprogram.] RAM i, uito"ut.a by the locator, if it is not initialized in , the Program. ' Modifier 'auto' or No modifier' if inside the function i block, *.un, ttt"t" is ROM allocation for the variable by the to"uto, if it is initialized in the progftm' There is nb nnU allocation bY the locator' . Modi f i er . unsi gned' i smodi f i er f or ashor t or i nt or l ong Oata type. it ii a directivc to permit only the positive valuei of t6, 32 or 64 bits' respectively' .Modi fi er.stati c.decl arati oni si nsi deafuncti onb| ock. ' Modi f i er r egi st er decl ar at i oni si nsi deaf unct i onbl ock' ' ' Modifier intemrpt' It directs the compiler to save all processor registers on entry.to the function codes and restort trtt*"on ittu'n frornthat function' ' Modifier extern' It directs the compiler to look.for the data type lt"furation or the function in a module other than the one cunentlY in use' . A t*.hasd"t elements ananged as branches' if.e Use of Conditions, Loops and Infinite Loops: . Conditional statements arc used many times' r If a defined condition (s) is fulfilled, the statements within tnt tuttv Uotts uittt the condition are executed' otherwise the irognrn proceeds to the next statement or to the next set of statements' . Sometimes a set of statements is repeated in a loop' Clneratty, in case of array, the index changes and the same sefis repeated for another element of the array' . Infinite loops are never dosired in usual programming' ' The program will never end and never exit or proceed further to the codes after the looP' . Infinite loop is a feature in embedded system Programming SummarY o MacroS are used when short functional codes are to be inserted in a number of Places' o The basic C programming elements are the data types' data structures, modifiers, cJnditional statements and loops' function calls, multiple functions' function queues and service routine queues' o Infinite looping is a greatly *ied feature in embeclded tyttttnt, as'it feeps u -att or system ready for execution whenever called to run' 3.4 Use of Pointers Pointersarepowerfultoolswhenusedcorrectlyandacgordingto ;;rt i" basic principles. Exernplary uses are as follows. Let a byte each be stored at a memory address' 3. r2 Embedded Let a portA in system have a buffer register that stores a byte. Now a program using a pointer declares the byte at port A as follows: 'unsigned bye *portA'. [Pbyte *portA.] The * means 'the contents at'. This declaration means that there is a pointer and an unsigned byte for portA. The compiler will rcserre one memory address for that byte. Consider .unsigned short *timerl'. A pointer timerl wilt point to t.wo bytes, and the compiler will reserve two memory addresses for contents of timerl. o Consider declarations as followg void *portAdata; The void means the undefined data type for portAdata. The compilcr will allocate for the *portAdaia without any type check. . A pointer can be assigned a constant fixed address. Consider two preprocessor directives: .# define portA (volatile unsigned byte *) Od000' and .# define PIOC (volatile unsigned byte t) 0xl00l'. . Alternatively, the addresses in a function can be assigned as follows. 'volatile unsigned byte t portA : (unsigned byte *) 0x1000' and 'volatile unsigned byte *PIOC = (unsigned byte *) 0xl00l'. An instruction, 'portA +r;' will make the portA pointer point to the next address and to which is the PIOC. . Consider, unsigned byte portAdata; unsigned byte fportA: &portAdata. The first statement directs the compiler to allocate one memory addrpss for portAdata because there is a byte each at an address. The & (ampersand sigr) means 'at the address of,. This declaration means the positive number of 8 bits (byte) pointed by portA is replaced by the byte at the address of portAdata. The right side of the expression evaluates the contained byte from the address, and the left side puts that byte at the pointed address. 3.4.1 I\ruLL Pointer A NULL pointer is a special type of pointer which does not points to valid pointer or to any other variable or an aray. ProEamming Concepts and Embedded ProEamming 3.13 Null pciintem can be used to place holed at a pointer does not point anywhere at the moment and that should not use the "contents of'operator on it. . A NULL pointer declares as following: '#define N{.JLL (void*) 0x0000'. . NULL pointer is very useful. Consider a statement: 'while (* RTCSWT_LisI. ListNow -> state != NULL) { numRunning #,'. . When a pointer to ListNow in a list of software timers that are running at psent is not NULL, then only execute the set of statements in the given pair of opening and closing curly braces. . One of the important uses of the NULL pointer is in a list. o The last element to point to the end of a list or to no more contents in a queue or empty stack, queuc or list. Summary Pointers are needed in number of situations, for example, port bit manipulation and read or write. 3.5 USE OF FUNCTION CALLS Functions are useful in such a way that they are used to exccute repeated codes as a separate program. The function contbins various parts like declaration, calling and definition of the function. A special function for starting the program execution is 'void main (void)'. Given below are the steps to be followed when using a function in the program. 3.5.1 Declaring a function Just as each variable has to have a declaration, each function must be declared. Consider an example. Declare a function as follows: 3. 14 Em,bdded Systems int run (int indexRTCSWT, unsigned int maxlength, unsigned int numTicks); Here int specifies the returned data type. The run is the function name. There ar a^rguments inside the brackets. 3.5.2 Defining the statements in the function Just as each variable has to be given the contents or value, each function statements. Consider the statements of the functiort 'run'. These are within a pair of curly bracps as follorys: int RTCSWT:: run (int indexRTCSWT, unsigned int mar{.jlrgth, unsigned int numTicks) { . . . } The last statement in a function is for the return and may lso before returning an element. 3.5.3 Call to a function Consider an example: if (delay_F =: true & & SsTDelayEnable : true) TSR-Delay ( ); Programming Concepts and Embedded Programmine 3. 15 Function 'run' arguments indexRTCSWT, maxlength and numTicks original values in the calling program during execution of the codes will remain unchanged. The advantage is that the same values are prcsent on lturn from the function. The arguments that are passed by the values are saved temporarily on a stack and retrieved on rqturn from the functiOn. 3.5.5 Passing the References When an argument value to a function passes through i pointer, that function can change this value. On returnin! ftom that function, the new value will be available in the calling fuilction or another function called by that function. Summary o Software dosignors must learn the uses of pointers in depth. e The C program uses passing the variables value by reference to the function, pointers, null pointers and function pointers. 3.6 MULTIPLE FIJNCTION CALLS IN CYCLIC ORDER IN THE MAIN One of the most common methods is for the multiple function- calls to be made in a cyclic order infinite loop of the main. The following diagram illustrates it: There is a several times call and on fulfilling a condition. The call can occur can'be rcpeatedly made. On each call, the values of the arguments given within the pair of bracket pass for use in the function statements. 3.5.4 Passing the Values (elemenh) The values are copied into the arguments of the functions. When the function is executed in this way, it does not change a variable's value at the called progam. A frrnction can only use the copied values in its own variables through the arguments. Consider a statement, run (int indexRTCSWT, unsigned int ma:<Length, unsigned int numTicks) t . . . ) voumarrtt { I I Programming model for multiple function calls in mainfunction 3.6.1 Function Pointers, Function Queues and Interrupt Services Routines Queues: Let the * sign not be put before a function name, but there are arguments within the pair of btaokets, and the statements for those executed on a call for the function. The statements ard inside a pair of the curly braces. Consider the following example: Example: typedef unsigned char intSbit; # define intSbit boolean #deJinefalse 0 # define true I voidmain (void) { Programming Concepts and Efnbedded Programming 3.17 /* Tlrc Declaratiorv of all variables, pointers, furctions here and also initializations here*/ uns i gtu d c hm * po rt Adat a ; boolean charAFlag; boolean clreckPortACh* ( ) ; void inPortA (unsigned char *); void decipherPortAData (unsigtud cfu, *); void encryptPortAData (unsisned char ); void outPortB (unsigrred clnr r); while (true) { /* Codes that rcPeatedlY erccute / /t Functionfor availability cleck of a clnracter at port A*/ while (charAFlag !: true) checkPortAClur 0; /* Functionfor reading PortA character*/ inPortA (unsigned char *portAdata) ; /* Functionfor deciPhering V deciphe rP ortA Data (uns igne d char *portAdan) ; /* Functionfor encoding *I encryptPortAData (unsigned char *portAdata) ; /*Functionfor retransmit output to PortB*/ outPortB (uns igned char *portAdata) ; ] ; ] Consider a declaration, 'boolean checkPortAChar ( );'. 'checkPortAChar' is a function, which returns a Boolean value. Now, checkPortAChar is itself a pointer to the starting address of lncfrrdeF e3 ) 3. 18 Embdded Systems the statements of the function inside the curly braces without the star sign before it. The program counter will fetch the address of checkPortAChar, and CPU sequentially executes the function- statements from here. ' Now, let the * sign be put before the function. '*checkPortAChar' will now refer to all the compiled form statements in the memory that are specified within the curly braces. Consider a declaration in the example, 'void inPortA (unsigned char *);' . inPortA means a pointer to the statements of the function. Inside the bracket, there is an unsigned character pointed by some pointer. rinportA will refer to all the compiled form statements of inPortA. (* inPortA) will refer to calls to the statements of inPortA, What will a statement, 'void create (void (rinPortA) (unsigned char *), void *portAStach unsigned char port Apriority);' mean? First modifier'void' means crate function does not return any thing. 'create' is another function. Consider the argument of this function 'void (*inPortA) (unsigned char *portA data)'. (*inportA) means call the itcn of inportA the argument of which is 'unsigned char *portAdata' The second argument of create function is a pointer for the portA stack at the memory. The third argument of create function is a byte that defines the portAfority. An important lesson to be remembered from above discussion is that a returning data type specification (for example, void) followed by'(ffunctionName) (functionArguments)' calls the statements of the functionName using the functionArgumentg Proprammins Conceots and Embedded Prosrammine 3.19 and on a rturn, it retums the specified data object. We can thus use the function pointer for invoking a call tb the function. When there are multiple ISRs, a high priority intemrpt service routine is executed first and the lowest priority, last. It is possible that function calls and statements in any of the higher priority intemrpts may block the execution of low priority ISR within the deadline. How is the deadline problern for low priohty foutines to be solved? One solution is by using the function pointers in the routines, and forming a queue for them. The functions are then executed at a later stage. Summary o An innovative concept is use of function queues and the queues of the function pointers built by the ISRs. o It reduces significantly the ISR latency periods. o Each device ISR is therefore able to execute within its stipulated deadline. 3.7 EMBEDDED PROGRAMMING IN C++ 3.7.1 Objected Oniented Programming An objected oriented language is used when there is a need for re- usability of the defined object or set of objects that are common within a program between many applications. When a large program is to be made, an object-oriented language offers many advantages. Data encapsulation, design of reusable software components and inheritance are the advantages derived from the OOPs. An object-oriented language provides for defining the objects and methods that manipulate the objects modifring their definitions. It provides for the data and methods for encapsulation. An object can be characterized by the following: . An identity, a reference to a memory block that holds its state and behavior. 3.20 Embedded Systems . A state (its data property, fields and attributes). . A behavior (method or methods that manipulate the state ofthe object). . In a procedure-based language, like FORTRAN' COBOL, Pascal and C, large programs are split into simpler functional blocks and statements. . In an object- oriented language like Smalltalk, C+r or Java, logical groups (also known as classes) are first made. Each group defines the data and the methods of using the data. o A set ofthese groups then gives an application program. . Each group has internal user-level fields'for the data and the methods of processing that data at these fields. . Each group can then create many objects by copying the group and making it functional. Each object is functional. . Each object can interact with other objects to process the user's data. . The language provides for formation of classes by the definition of a group of objects having similar attributes and common behavior. . A class creates the objects. An object is an instance of a class. Programming advantages of Cr-t g++ is an object oriented Program (OOP) language, which in addition, supports the procedure oriented codes of C. Program coding in C++ codes provides the advantage of objected oriented programming as well as the advantage of C and inJine assembly. Prograrnming concepts for embedded programming in C+r are as follows: . A class binds all the member functions together for creating objects. The objects will have memory ProEamming Concepts and Embedded Programnring 3.21 allocation as well as defauh assignments to its variables that are not declared static. Let us assume that each software timer that gets the count input from a real time clock is an object. Now consider the codes for a C+r class RTCSWT. A number of software timer objects can be created as the instances.of RTCSWT. A class can derive (inherit) from another class also. Creating a child class from RTCSWT as a parent class creates a new application of the RTCSWT. Methods (C functions) can have same name in the inherited class. This is called method overloading. Methods can have the same name as well as the same number and type of arguments in the inherited class. This is called method overriding. These are the two significant features that are extremely useful in a large program. Operators in C+r can be overloaded like in. method overloading. There is struct that binds all the mernber functions together in C. But a C++ class has object features. It can be extended and child classes can be derived from it. A number of child classes can be derived from a common class. This feature is called polymorphism. A class can be declared as public or private. The data and methods access is restricted when a class is declared private struct does not have these features. Disadvantages of C+r Program codes become lengthy, particularly when certain features of the standard Cr+ are used. Examples of these features are as follows: Template. Multiple Inheritance (Deriving .a class from many parents). I I ) i I l I \ I t I }. a a 3.22 Embedded Systems Exceptional handling. . Virtual base classes. . Classes for IO Stroams. [Two library functions are cin (for character(s) in) and cout charactlr (s) out). The I/O 'stream class library provides for the input and output streams of characters (bytes). It supports pipes, sockets and file management features. 3.7.2 Embedded Programming in C+ + Embedded system codes can optimized when using an OOp language by the following: . Declare private as many classes as possible. It helps in optimizing the generated codes. o Use char, int and boolean (scalar data types) in place of the objects (reference datatypes) as arguments and use local variables as much as feasible. . Recover memory already used once by changing the reference to an object o { special compiler for an embedded system can facilitate the disabling of specific features provided in C+r. . Embedded C++ is a version of C+r that provides for a selective disabling of the above features so that there is a less runtime overhead and less runtime library. . The solutions for the library functions in an embedded C#t compiler are also reentrant. . So using embedded C# compilers or the special compilers make the C+r a significantly more powerful coding language than C for embedded systems. GNU Compiler ' . GNU C/C++ compilers (called gcc) find extensive use in the C++ environment in embedded software development. Procramminc Conceots and Embodded Prromamrninc 3.23 Embcddod C++ is r ncw pogramming tool with a compihrtrd providcs a smdl nnrtimc library. o It satisfies small nurtime RAM needs is.by sclectively deronfiguring featurcs like,' template, multiple inhritrnce, virtual bose clecs, c0c. . Whe,n ttrere is a less runtime overlrcad ana *en tlre less runtimc library using solutions 6r availSlc. Sclcctively rcnroved (de-configpred) ftoturcs could be templati, run rilrc t'"e idcntificatidr, muhiplc inhcritanoc, cxccpional lnndling virtual base clrsscs, IO streams and foundcirnchss. An embcddod sy*cm (C++ compiler (drcr than gcc) is Diab compilcr ftom Diab lhtr. It also pr,ovirles thc trga (embedded system processor) spccific opimizatior fic @des. Thc run- line analysis tools chec* $c e,xpec'tcd nrn time cnu and givc a profil that is visually fuscractive. Srmnery o Embedded C++ is a Cr+ yeniion, which makes largs Fogram development simpler by providing object orientod prrognmming feahres of using an object, which bitds stat and behavior and which is dcfind by an instrnce of a chss. o Diab oompihr has two spccial festurs - processor specific code opimizdion and run tirne analysis tools for finding expected run time errors. 3.8 'C' PROGRAM COMPILER A compiler generates an object file. The object file is generated on compilation program while an executable file is.required, which has the source codes having the absolute addresses.. g For compilation for.the host alone, the compiler can be turbo C. Turbo C# or8orland C and Borland C++. 3.24 Embodded SYste$ , - . Two *rnpit"ot " needed' One compiler is- for $e host cor-nputer *'tti"tt does thc devolopment and design and "ft"iftt t"Jingcr{ debugging: The second compiler is a ' cross-comPiler. r There is a popular freeware calhd GNU CIC++ "Apiftt and ffi Asl lM assembler for 68HCl1' , ' , A GNU compiler is configurable both as host compiler 'as well ss cro$'Gornpiler':It supports 80x86' Window 95/NT, 80xS6 Red Hat Linux and scveral other platforms. ' It supports 80x86, 68HCll, 80960' PowerPC and ' several other targBt system processors' 3.8.f Crcss ComPiler The cross compiler runs on a host machine' but develops the machine codes io, u tt g"ted system ( Processor of the embedded system). It means that ; target system can emulate and simuiate tire application system on the host . Thet ar get sy$em. speci f i cor mul t i pl e. choi cecr oss. compitersttrai are onuilubtt commercially may be used' . These are available for most enrbpddod system microprocesqpn and miorocontrollers' The IAR System' Swedin, offers cross-compilers for many targets' . Thet ar get scar r beof t hePf ar r r i l yor S05l f ami l y, 68HCl f famitY or 80196 familY' ' FCM is another closs compiler for the PIC (hogrammable Intemrpt Controller) microcortroller i*''ty, PIc 16F84 or l6-C76, l6F876.The host also runs thecross-compilcrthatoffersanintcgrateddevelopment envincnment Erecutablc File Inanembeddedsystemdesig&asthefinalstep'thebytes.mustbe olaced at thc ROM after irnpildiom' A 'C' prognm helps to ffit""; ;hJr*i nr. .*crutabl" filc is tlre file that a device Procrammine Concepts and EmHded Prcgra4ming 3.25 .program uscs to put (store or buri data' constants, vectors, tables, and-strings, and ttre source codes in the ROM A locator file has the final informdion of memory allocation to the codes, data initialization data and so on. Thi locator then uses the allopation map file. and generafes the source code within the allocated addresses. The ROM has the following sections: : . Machine (Execrrtable) codes for the bootshap (rcse0 program .. . Initialization (default) data at shadow ROM for copying into the RAM during execution . Codes for the application and.intemrpt service routines . System configuration data needed br the execution the codes o Standard data or vectors and tables . Machine codes for the device mana.ge and device drivers Summary Use of appropriate compilers and cross compilers is essential in any embedded software development 3.9 SOTTRCE CODE ENGINEERING TOOL FOR EMBEDDED C/C+ + A source code engineering tool is of great help for source-code developmen! compiling and cross compiling. The tools are commercially available for embedded C/C+r code enginecring, testing and debugging. The features of a typical tool are comprehension, navigation and browsing editing debugging configuring (disabling and enabling the C+r features). A tool for C and C+| is SNiFF+. It is 326 Emb?ddcd frotn WirdRirct Sysuns. A vcrsion SNiFF+ PRO code as well as debug module. Mrin fcaturcs ofthe tool are as follows: It seschas and li$s thc definilions' symbols' hierarchy of the classcs, and chss inhritsnoc tslcs It searches and liss ilre dependcncios of symbols and dcfincd symbols, variablcs, ftnrctiors (mcfiods) and othcr symbols. It mqritors' cnabhs and dis.bh tlrc implcrnentatiolt Yirtual frmctions. It fu& dtG ftll cftct of ur.y co& dtdtge on dtc soume codc. ft scsshcs dd lists trc dcpcn&ncies md hicrarchy of irchdod hcldcr fihs. !t navigScs to ard fio barrccn thc imphrnentation and synrbol dech*ion ft navigUes to and Ao bctwoen tlrc ovcrridden and overriding nrethods. [Overriding me0rod is metlrod in daugbtcrihss with same namc ard srmc number and types of arguments as in the pastt class. Overriddcn ithttoO is tlre rtthod of thc porcnt chss, which has becn Fdfinod *the daugfttcr olas. It browscs fftrou$ information rcgnrding instantiation (objoct creation) of a chss. ft browscs ftturgh information encapsulation of variables among the mernbers and brswscs through the public, private and protected visibility of ttre members' It browses through object comportent relatiorrships' It automatically rcmoves enor- prone and unused tasks' It provides easy and automated search and replacement' Proerammins Concepts 8rd E nbdded Pnogramndm 327 Snmmaty The embeddcd softrrare designer for sophisticated applications uses a soure code engineering tool for program coding, profiling, testing and debugging of embedded system softrrare. 3.IO OPTIMIZATION OF MEMORY NNEDS When codes are madc compact and fi1ted in small memory af,eas without affecting the codo performance, it is called memoty optimization. It also reduces the total number of CPU cycles, and thuq the total enerry requircments. Thefollowing are used for optimizing the use of memory in a system. Use declarotbn os unsigned hyte If there is a variable, which always has a value between 0 and 255. When using data sfuctures, limit the maximum size of queues, lists and stacks size to 256. Byte arithmetic takes less time than integer arithmetic. Foltow a rule thot uses wsigned bytes for a short ond a short for an imeger It is used to optimize use of the RAM and ROM available in the system. Avoid if possible the use of 'long' integers and 'double'precision floating point values. Avoid use of librarylundtons if a simpler coding is possibla Library functions arp the general functions. Use of general fuirction needs mor memory in several cases. Follow a rule that avoids use of library functions in case a generalized function is expocted to take more memory when its coding is simple. t o a a ffi"er lenows fully the instruction s4 or the target ptocessor, assimbty codes must be used This also allows the efficient use of mem-ary.The device driver oro**ri nassembl yespeci al l yprovi deeffrci encyduetothe ;;Hil;tne Uit r"ir.."t instructions for the control and status .*gi ' t' *o"l ythefewassembl ycodesforusi ngthedevi ce.V0 ffi addressei, confiol and status registers are nee&d. The best lt" it made of available features for the given applications' ;;;Uy coding also helps in coding for atomic operations' A modifier register can be used in the C progam for-fast access to a It"Or*ifV is"O nutiaUle.If portA Oata is tequently employed' it is used as follows, 'register unsigned bye portAfall" The ;J.'* register directs'the compiier to place portAdata in a general-purpose register of the processor' Asar ul e, uset heassembl ycodesf or si mpl ef unct i onsl i ke ,onngoting the device tontroi register, port addresses and bit ;;dilt6ns if the instruction Gt is clearly understood' Use |,[ffit codes for the atomic operations for increment and uJAiti#Ut modifier register for a frequently used variable' Cating afunction carrsr contert saving on a memttry stack and on retirn the cont& is retrieved' Thisinvolvestimeandcanincreasetheworst.caseintemrpt. latcncy. There i, n,Jiner inline. when the inline modifier is ;r.4lh. oompiler inserts the actual codes at all the places when t heseoper at oo* _o* d. Thi sr educest het i meandst acl t oulir,"ui, in the function call and retum. But" this is at the cost o more ROM being needed forthe codes' If used, it increases the size of the prograT but gives r faster speed. usini tne modifier directs the compiler to put th, ;;; flt tr," n nition (in curlv u9:"t) instel! -of calling tha' n n"tion. As a rule, use inline modifiers for all frequently use ,r"ii *t, of codes in trr" function or the operator overloadin functions if trre noM is available in the system' A vacant ROI\ memory is an unused resource' Why not use it for reducing th worst-case rnt ^rpi-iutencies by eliminating the time taken i fr"quJ;e and ietrieval of a program context? .. ProprammineConcepts andEmbeddedProgamming !.29 As long as sharcd dota problem does orise, the ase of global variables can be optimired. These are not used as the arguments for passing the values. A good function is one that has arguments to be passed. The passed values are saved on'the stacks in caS'of intemrpt service calls and other firnction calls. Besides obviaing the need for repeated declarations, the use of global vdriables will thus reduce the worct{ase intemrpt-latency and the time and stack overheads in the function call and return. But this is at the cost of the codes for eliminating shared data problem. When a variable is declared statiq, the processor accesses with less instruction than from the stack. As a rule, use global variables if shared data problem are tackled and use static variables in case it needs saving frequently on the stack. Combine two functions if possible. As a rule, whenever feasible combine two functions of more of less similar codes. . Bringing the tasks into an initiated task list will reduce the fr,equent interactions with the OS and context savings and retrievals stack and time overheads. Optimize the RAM use for the stacks. It is done by reducing the number of tasks that interact with the OS. One function calling another function and that calling the third and so on means nested calls. Reduce the number of nested calls and call at best one more function from a funition. This optimizes the use of the stack. As a rule reduce use of frequent function calls and nested calls and thus reduce the time and RAM memory needed for the stacks, respectively. r Use if feasible, alternatives to the switch statements with a table of pointers to the functions. This saves processor time in deciding which set of statements to execute while performing the conditional tests all down a chain. o Use the delete function when there is no longer a need for a set of statements after that execute. As a rule, to fre the RAM used by a sct of sta0crrasa use the detete function and destructor functions. . When using C++, configure thc compilcr for not permitting the muhi-inhcritance, bmplaleq exccptional handlirry; rrcw g1ile castsr virtuEl basc classei, ard namcspe$. As r nrle, for using Cr+, usc the classes without muhiple inheritance, without template, with nrntime identification and with throwable occeptions. Sumnery Embedded software d$igners must us various standard ways for optimizing the memory needs in a system.