Sei sulla pagina 1di 16


he programming in an embedded environment -ui be performed using various levels of languageslike assembly language, procedural languages and object oriented language. This unit aims at introducingthe various programmingconcepts and the embedded implementation in those languages. The programmingconcepts will also includethe memoryoptimization tools. techniques and the sourcecodeengineering

3.1.1. Assembty Language Programming

Assembly languagelies in betweenthe 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 assemblylanguagein the machinelanguage. Advantages . It gives a precise contol of the processor internal devicesand full useof processor specific featuresin its instructionsetand its addressing modes.


Embedded The machine codes are compact. This is becausethe codesfor declaringthe conditions,rules, and data type do not exist. The systemthus needsa smallermemory' Excess memory needed does not depend on the It programmerdatatype selectionand rule-declarations' functions library and specific compiler it ato not the 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 automaticwashing machineor an automaticchocolate vendingmachine.

Propramming Conceptsand EmbeddedProgramming


Summary High level language programming makes the program cycle short, enablesuse of modular programming development 'and lets us follow sound software engineering approach principles.

The 'C' program elements,headerand source files and preprocessor directivesareas follows:


tligh Level Language


Include Directive for the Inclusion of Files

currently usedare the high level All the programminglanguages programming language are the of languagls. The constructs gnifisf; fke structures. lnterpreter and the Compilers are the system progftms which are used to convert the high level in the machinecodes. language Advantages cycle is shortfor complexsystems The development ease' provideprogramming l. Data lype declarations 2. Type checkingmakesthe programlessproneto error' make the 3. Control structuresand conditional Statements program-flowpath designtaskssiritple' specificcodesexists' 4. Portability of non-processor Additional advantagesof C as a high level languages It is a funguage between low (assembly) and high level tanguage.tnseiing the assemblylanguagecodes in- between is also catta ln-line assembly.A direct hardwarecontrol is thus program part the of feasible by in-line assembly,and the complex can be in high-level language.

Any C program first includesthe headerand source files that are readily available Example functionsLibrary */ # includesemlib.h /* IncludeSemaphore Include is a peprocessordirective to includethe contents(codes or data)of a file. IncludingCodesFiles: Theseare the files for the codesalreadyavailable.For example,#include"prctlHandlers.c". . . Including Constant dataFiles: Theseare the files for the codesand may havethe extension'.const'. Including Stings data Files: Theseare the files for the '.strings'or'.str.' or ' stringsand may havethe extension '.txt. Includinginitial dataFiles:Thereare files for the initial or default data for the shadow ROM of the embedded system. Files:'These are the files for Including basicvariables thq local or global static variables that are stored in the RAM becausethey do not possesthe initial (default) values.



. .

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 # include Srnath.h>'.

Pros:amming Concents andEmbedded Prosrammins 3.5 global IntrEnablea variableof Booleandatatype and is volatile. Preprocessor Constants: "# define false 0" is a prepiocessor directive.It means,it is a dircctive before 'false' as 0. processing to assume Summary o Preprocessor constants, variables and inclusion, of configuration files, text files, header files and library functions are usedin C programs.

Also included are the headerfiles for the codesin assembly, and (conio.h), for the VO operations for the OS functionsand RTOS functions. The difference between inclusion of a headerfile, and a text file or data file or constants file is described as follows: modules. l. The headerfiles are well testedand debugged 2. The headerfiles provideaccess to standard libraries. 3. The headerfile can includeseveraltext file or C files. 4. A text file is descriptionof the texts that contain specific information.

o Functions are used when the requirement is that the code shouldbe compiledonceonly. o A function may return nothing or a Boolean value or an integer or any primitive data type.


3.2.2 Source Files



Source files are program files for the functions of application software.The sourcefiles needto be compiled.A sourcefile will also possessthe 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.

A macrois a collection thatis defined of codes in a program by a name. It differsfrom a function in the sense thatoncea macrois putsthecorresponding defined by a name, thecompiler codes for place it at every wherethatmacronameappears Whenever the name of themacroappears, thecompilerplaces the codesdesigned for it. Macros,called test macrosor test vectors arealsodesigned andused for debugging a system. How doesa macro differ from a function?The codesfor a functionare compiledonceonly. On calling that function,the processorhas to save the context, and on return restorethe context. Macrosare usedfor short codesonly. This is because, if a (context function call is used insteadof macro,the overheads savingand otheractionson functioncall and return)will take a time.

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 preprocessordirective. It me,ans,it is a directive before processing to consider



3.3.2 Functions
with values passed The functions executesa named set of codes Also returns a data Uy, tt. calling program through its argumelts' the context saving ;ilj"; when It'is not declarei as voii, It has and retrieving overheads. Main Function and either (i) Declarations of functions and data b/ps,typedef and calls Executes a named s"i or codes,calls a set of functions, oiift" inttt-pts the ISRs or (ii) startsan OS Kernel' Interrupt senice Rodine or Daice Drtver and Declarations of functi6ns and data Epes, one$et other so that Executes a named set of codes' Must bc short Must deadlines' the within sourcesof intemrpts arc also serviced shared the to solution a be either a reenfa'; routine or must have dataproblem. RecurciveFunction function also' A function th4 calls itself. It must be a reefitrant due to systems embeddcd Most often ib use is avoi&d in memory consmints. Reentiant Function and routines Reentrantfunction is usableby the severaltasks synchronouslY. o o


Vfott C compilersdo not take a Booleanvariable

is used' For I data type appropriate for the hardware unsigned the only example, u iO-iit'timer can have 65535 to 0 short data type, and its range can be from the by clear only. The tyi.Otf is also uJed' It is made following examPle' no1processthe declarationas { compiler version may ;unsigned character'can then be an unsignedbyte' The as follows: It canthen be declared usedas a Oata"typ"'


Use of Data Structures of any progtam' A few A data structureis an importantelement array,queue, in,portun,data structur", ur. stack,one-dimensional amY)' lookup circular queue' plpe; u tuUtt (two dimensional table,hashtableand list' exemplaryusesof The following sectiongivesthe usesand shows lists andtrees stacks,alTays' queues, Queue ' It is a sfiucturewith a seriesof elementswith the first for an operation'An operationcan be element*;ftg doneonly in thi first in first out (FIFO) mode' by any . lt is usedwhen an elementis not to be accessible FIFO' the index andpointerdirectly,but only through ' An elementcan be insertedonly at the end in the series waiting for an operation' of elements the , ' There are two pointers, one for deleting after after operationand other for inserting' Both increment an oPeration. Example is to be printedin Print buffer. Eachcharacter FIFO mode'

' 3.3.3 Use of Data TYPes ,.Wheneveradataisnamed,itwillhavetheaddress(es) of addresses allocatedat the memory'The number 'C' allowsthe type' uponiht data Jepends allocated tYPes' data followingPrimitive byte (8 bit)'^unsigned . The char (8 bit) for characters, int ttt"tt (16 ;it), strort(tO bit), unsigne{lnt.OZ tit)' double and (32 bit), il;i'oouutelo+ bil), float (32 bI) 'byte' as a not takethe iOc Uit). tCJrtaincompilers-do ,char' of ls thenusedinstead The oatatype'd"rinition,



Stack .

. It is a structurewith a seriesof elementswith its last element waiting for an operation. An operation can be done only in the last in first out (LIFO) mode. It is usedwhen an elementis not to be accessibleby any index or pointerdirectly,but only throughthe LIFO. An elementcan be pqshed(inserted)only at the top in the seriesof elements still waiting for an operation. There is only one pointer used for pop (deleting) after the operationas well as for push(inserting).

Programming 3.9 Concepts andEmbedded Proerammins The dimensionof an array equalsthe numberof indices that are neededto distinctly identiff an array-element. Indices start from 0 and are *ve integers Matrix or a pixel in an imageframe.


. . .

List . . Eachelementhasa pointerto its next element. Only the first elementis identifiable and it is done by list-top pointer (Header). No other 'element is directly. identifiableand henceis not accessible By going through the first element, and then elements,an consecutivelythrough all the succeeding element can be read, or read and deleted, or can be elementor replacedby another addedto a neighbouring element.

o Pointers incrementor decrementafter an operation.It depends on insertionor deletion. Example Pushingof variableson intemrptor call to anotherfunction. Array (One Dimensional Vector) . It is a structure with a series of elementswith each elementaccessible by an identifier nameand an index. o Its elementcan be usedand operatedeasily. It is used when each element of the sructure is to be given a distinct identity by an index for easy operation.Index starsfrom 0 and is fve integers. Example ts: 12 * l2ts[0] Total salary, ts is 12timesthe first monthsalary. Multi-dimensional Array . It is a structurewith a seriesof elementseach having anothersub-series of elements. . Each element is accessible by identifier name and trvo or more indices. . It is used when every elementof the structureis to be given a distinct identity by two or more indicesfor easy operation.


Example A series of taskswhich are active, each task has pointer for the next task. Tree . . . . It has two or more brancheseach having a daughter element. Each daughter element has two or mone daughter elements. The last one doesnot have daughters. Only the root elementis identifiable and it is done by the treetoppointer(Header).

o No other element is identifiable and hence is not ' acressibledircctly. By traversingthe root element,then proceeding continuously through all the succeeding daughters, a tree element can be read or read and deleted, or can be addedto anotherdaughteror replaced by anotherelement.

3.10 . A t*.hasd"t

anangedas branches' elements

.Thelastdaughter,callednodehasnofurtherdaughters'l . A binary tree is a tree with a maximum of two daughters in eachelement' (branches) Example Anexampleisadirectory.Ithasnumberoffile.folders.Eachfile. so on' In the end is a folder has a numbtt oiott'tt file foldersand file. I


Loopsand Infinite Loops: Useof Conditions,

arc usedmany times' Conditional statements r If a defined condition (s) is fulfilled, the statements executed' within tnt tuttv Uotts uittt the condition are statementor otherwise the irognrn proceedsto the next to the next set of statements' . Sometimes a set of statementsis repeated in a loop' and the Clneratty, in caseof array, the index changes array' the of element for another samesefis repeated . Infinite loops are never dosiredin usual programming' ' The program will never end and never exit or proceed further to the codesafter the looP' . Infinite loop is a feature in embedded system

3.3.5 Use of Modifiers areasfollows: of modifiers Theactions I function 'auto' a outside. if or No modifier' ' Modifier there is ROM allocationfor the that rnt-tblock, variableuvtr''lo.uto'ifitisinitia|izedintheprogram.] in Programming if it is not initialized RAM i, uito"ut.aby thelocator, , theProgram. ' Modifier 'auto' or No modifier' if insidethe function i SummarY for the variable to be block, *.un, ttt"t" is ROM allocation o MacroS are used when short functional codes are is There progftm' the in initialized is it if to"uto, by the insertedin a numberof Places' bYthelocator' nb nnU allocation data o The basic C programmingelementsare the data types' .Mo d i fi e r.u n si g n e d 'ismodifier for ashor tor intor long loops' and structures, modifiers, cJnditional statements positive queues and type. it ii a directivcto permitonly the Oata function calls, multiple functions' function respectively' bits' 64 valueiof t6, 32or serviceroutine queues' .Modifier.static.declarationisinsideafunctionb|ock. is a greatly *ied feature in embeclded
o Infinite looping -att

or systemready for execution 'Mo d i fi e rre g i ste rd eclar ationisinsideafunctionblock' ' tyttttnt, as'it feeps u whenevercalledto run' ' Modifier intemrpt'It directsthe compilerto saveall on entry.tothe functioncodesand registers processor restorttrtt*"on ittu'n frornthatfunction' 3.4 Useof Pointers ' Modifier extern'It directsthe compilerto look.for the other Pointersarepowerfultoolswhenusedcorrectlyandacgordi datatype lt"furation or the functionin a module areasfollows.Let a byte uses Exernplary ;;rt i" basicprinciples. in use' thantheonecunentlY address' at a memory be stored each



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: 'unsignedbye *portA'. [Pbyte *portA.] The * means 'the contentsat'. This declaration meansthat there is a pointer and an unsignedbyte for portA. The compiler will rcserre one memory address for that byte. Consider .unsigned short *timerl'. A pointer timerl wilt point to t.wobytes, and the compiler will reserve two memory addressesfor contents of timerl. o Consider declarationsas 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 preprocessordirectives: .# define portA (volatile unsignedbyte *) Od000' and .# define PIOC (volatileunsigned bytet) 0xl00l'. . Alternatively, the addressesin a function can be assignedas follows. 'volatile unsignedbyte t portA : (unsignedbyte *) 0x1000' and 'volatile unsignedbyte *PIOC = (unsignedbyte *) 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 statementdirects the compiler to allocate one memory addrpssfor portAdata because there is a byte each at an address. The & (ampersand sigr) means 'at the address of,. This declarationmeansthe positive numberof 8 bits (byte) pointed by portA is replacedby the byte at the addressof portAdata. The right side of the expression evaluates the containedbyte from the address, and the left sideputsthat byte at the pointedaddress.

ProEamming Concepts andEmbedded ProEamming 3.13 pciintem Null can be usedto placeholed at a pointer doesnot point anywhere at the moment and that should not use the "contentsof'operator on it. . A NULL pointerdeclares as following: '#define N{.JLL(void*) 0x0000'. . NULL pointer is very useful.Considera 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 openingand closingcurly braces. One of the important uses of the NULL pointer is in a list.

o The last elementto point to the end of a list or to no more contentsin a queueor emptystack,queucor list. Summary Pointersare neededin numberof situations, for example,port bit manipulationand reador write.


Functionsare useful in such a way that they are used to exccute repeatedcodes as a separateprogram. The function contbins various parts like declaration, calling and definition of the function. A specialfunction for startingthe programexecutionis 'void main (void)'. Given below are the steps to be followed when using a function in the program.

3.4.1 I\ruLL Pointer is a special typeof pointer whichdoes A NULL pointer notpoints to validpointer or to anyother variable or anaray.


Declaring a function

Justas eachvariablehasto havea declaration, eachfunction must be declared. Consideran example.Declarea function as follows:


Systems Em,bdded

unsignedint maxlength, int run (int indexRTCSWT, unsigned int numTicks); Here int specifiesthe returneddata type. The run is the insidethebrackets. Thereara^rguments functionname. 3.5.2 Defining the statementsin the function or value,each Justas eachvariablehasto be giventhe contents thestatements of the functiort'run'. Consider functionstatements. asfollorys: arewithina pairof curlybracps These unsigned int mar{.jlrgth, int RTCSWT:: run (int indexRTCSWT, int numTicks) unsigned

Function 'run' arguments indexRTCSWT, maxlength and numTicks originalvalues in thecallingprogram duringexecution of thecodes will remain unchanged. The advantage is that the samevaluesare prcsenton lturn from the function.The arguments that are passed by the values are saved temporarilyon a stackandretrieved on rqturnfrom the functiOn. 3.5.5 Passingthe References Whenan argument valueto a functionpasses throughi pointer, that function can changethis value. On returnin! ftom that function, thenewvaluewill beavailable in thecallingfuilctionor another functioncalledby thatfunction. Summary o Softwaredosignors must learn the usesof pointersin depth. e The C programuses passingthe variablesvalue by reference to the function, pointers,null pointersand functionpointers. 3.6 MULTIPLE FIJNCTION CALLS IN CYCLIC ORDER IN THE MAIN One of the mostcommon methods is for the multiplefunctioncallsto be madein a cyclic orderinfinite loopof the main.The followingdiagram illustrates it:

Programming Conceptsand EmbeddedProgrammine


in a function is for the return and may lso The last statement anelement. returning before 3.5.3 Call to a function

anexample: Consider : true) =: true& & SsTDelayEnable if (delay_F ( ); TSR-Delay There is a call on fulfilling a condition.The call can occur made.On eachcall, the severaltimes and can'be rcpeatedly given within the pair of bracketpassfor valuesof the arguments usein the functionstatements. 3.5.4 Passingthe Values (elemenh)

When of the functions. The values arecopiedinto the arguments the function is executedin this way, it does not change a canonly use variable'svalueat the calledprogam.A frrnction the copied values in its own variablesthroughthe arguments. a statement, Consider int ma:<Length, unsigned run (int indexRTCSWT, int numTicks) unsigned




voumarrtt {

andEfnbedded Concepts Programming Programming 3.17 /* Tlrc Declaratiorv of all variables, pointers, furctions here and also initializations here*/ unsigtu d chm *po rtAdata; boolean charAFlag; boolean clreckPortACh* ( ) ; void inPortA (unsignedchar *); void decipherPortAData (unsigtud cfu, *); void encryptPortAData (unsisnedchar ); clnr r); void outPortB (unsigrred while (true) { erccute/ /* Codesthat rcPeatedlY /t Functionfor availability cleck of a clnracter at port A*/ while (charAFlag !: true) checkPortAClur 0; /* Functionfor reading PortA character*/ inPortA (unsignedchar *portAdata); /* Functionfor deciPheringV rPortAData (unsigned char *portAdan) ; deciphe /* Functionfor encoding *I encryptPortAData (unsignedchar *portAdata); /*Functionfor retransmitoutput to PortB*/ outPortB (uns igned char *portAdata); ]; ] 'boolean checkPortAChar ( Consider a declaration, );'. 'checkPortAChar'is a function, which returnsa Boolean value. of is itself a pointerto the startingaddress Now, checkPortAChar

model Programming functioncalls in mainfunction for multiple 3.6.1 Function Pointers, Function Queuesand Interrupt RoutinesQueues: Services Let the * sign not be put beforea functionname,but thereare for those andthe statements within thepair of btaokets, arguments ard insidea on a call for the function.The statements executed thefollowingexample: Consider pairof thecurlybraces. Example: charintSbit; unsigned typedef # defineintSbitboolean 0 #deJinefalse # definetrue I voidmain(void){


Embdded Systems

the statements of the functioninsidethe curly braces without the star sign beforeit. The program counterwill fetchthe address of checkPortAChar, and CPU sequentially executes the functionstatements from here. ' Now, let the * sign be put before the function. '*checkPortAChar' will now refer to all the compiledform statements in the memory that are specifiedwithin the curly braces. 'void inPortA(unsigned Consider a declaration in theexample, *);'. char inPortA meansa pointer to the statements of the function. Insidethe bracket, thereis an unsigned pointedby some character pointer. rinportA will refer to all the compiledform statements of inPortA. (* inPortA)will referto callsto thestatements of inPortA, 'void create Whatwill a statement, (void (rinPortA)(unsigned *), *portAStach char void unsigned charportApriority);'mean? Firstmodifier'void' means crate function does not returnany thing. 'create'is another function. Considerthe argumentof this function 'void (*inPortA) (unsigned char *portA data)'.(*inportA)means call the itcn of inportAtheargument of whichis 'unsigned char*portAdata' The secondargument of createfunction is a pointer for the portA stackat thememory. The third argument of create functionis a bytethat definesthe portAfority. An importantlesson to be remembered from abovediscussion is that a returning data type specification(for example,void) followed by'(ffunctionName) (functionArguments)' calls the statements of the functionName using the functionArgumentg

Proprammins andEmbedded Prosrammine 3.19 Conceots and on a rturn, it retums the specified data object. We can thus usethe function pointerfor invoking a call tb the function. When there are multiple ISRs, a high priority intemrpt service routine is executedfirst and the lowest priority, last. It is possible in any of the higher priority that function calls and statements intemrptsmay block the executionof low priority ISR within the deadline.How is the deadlineproblernfor low priohty foutinesto be solved?One solution is by using the function pointers in the routines,and forming a queuefor them. The functions are then executedat a later stage.

Summary o An innovative conceptis use of function queuesand the queues of the functionpointersbuilt by the ISRs. o o It reduces significantlythe ISR latencyperiods. Each device ISR is therefore able to execute within its stipulated deadline.


3.7.1 Objected Oniented Programming is usedwhenthere is a needfor reAn objectedorientedlanguage usability of the defined object or set of objectsthat are common within a program between many applications. When a large program is to be made,an object-oriented languageoffers many advantages.Data encapsulation,design of reusable software are the advantages derived from the components and inheritance OOPs. providesfor defining the objects An object-oriented language and methods that manipulate the objects modifring their definitions. It provides for the data and methods for An objectcanbe characterized by the following: encapsulation. . to a memoryblock that holds its An identity, a reference stateand behavior.

3.20 . . .


A state(its data property, fields and attributes). A behavior (method or methods that manipulate the stateofthe object). In a procedure-based language, like FORTRAN' COBOL, Pascal and C, large programs are split into simpler functionalblocksand statements. In an object- oriented languagelike Smalltalk, C+r or Java, logical groups (also known as classes)are first made. Each group definesthe data and the methodsof usingthe data.

ProEamming Concepts andEmbedded Programnring 3.21 allocationas 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 considerthe codes for a C+r classRTCSWT. A numberof softwaretimer objectscan be createdas the instances.of RTCSWT. A class can derive (inherit) from another class also. Creatinga child classfrom RTCSWT as a parent class creates a new applicationof the RTCSWT. Methods (C functions) can have same name in the inherited class. This is called method overloading. Methods can have the samename as well as the same number and type of argumentsin the inherited class. This is called method overriding. These are the two significant featuresthat are extremelyuseful in a large program. Operators in C+r can be overloadedlike in. method overloading. There is struct that binds all the mernber functions togetherin C. But a C++ classhasobject features. It can be extendedand child classes can be derived from it. A number of child classes can be derived from a common class.This featureis called polymorphism.A class can be declaredas public or private. The data and methods access is restricted when a class is declared private structdoesnot havethesefeatures.

o A set ofthese groupsthen givesan applicationprogram. . Each group has internaluser-levelfields'for the dataand that dataat thesefields. the methodsof processing . Each group canthen createmany objectsby copyingthe group and making it functional. Each object is functional. Each object can interact with other objects to process the user'sdata. The languageprovidesfor formation of classesby the definition of a group of objectshaving similar attributes and commonbehavior. of a the objects.An object is an instance A classcreates class.

. .


l Programming advantagesof Cr-t I g++ is an object oriented Program (OOP) language,which in \ addition, supportsthe procedureoriented codes of C. Program of objectedoriented coding in C++ codesprovidesthe advantage t of C and inJine assembly. programmingas well as the advantage }. programmingin C+r are as conceptsfor embedded Prograrnming follows: . A class binds all the member functions together for creating objects. The objects will have memory


Disadvantages of C+r Program codes particularlywhencertainfeatures become lengthy, of the standard Cr+ areused. Examples of these features areasfollows:
a a

Template. (Deriving .a class from many Multiple Inheritance parents).

3.22 . .

Embedded Systems Exceptionalhandling. Virtual baseclasses. Classesfor 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 streamsof characters (bytes).It supportspipes, sockets and file management features. Embedded Programming in C+ +

Procramminc Conceots andEmbodded Prromamrninc 3.23

EmbcddodC++ is r ncw pogramming tool with a compihrtrd providcs a smdl nnrtimclibrary. o It satisfiessmallnurtimeRAM sclectively deronfiguring featurcs like,' template, multiple inhritrnce, virtualbose clecs, c0c. . Whe,n ttrereis a lessruntimeoverlrcad ana*en tlre less runtimclibraryusingsolutions 6r availSlc. Sclcctively (de-configpred) rcnroved ftoturcscouldbetemplati,run rilrc t'"e idcntificatidr, muhiplc inhcritanoc, cxccpional lnndling virtual baseclrsscs, IO streams andfoundcirnchss. An embcddod sy*cm (C++ compiler (drcr than gcc) is Diab compilcrftom Diab lhtr. It alsopr,ovirles thc trga (embedded processor) system spccificopimizatior fic @des.Thc run- line analysistools chec* $c e,xpec'tcd nrn time cnu and givc a profilthat is visuallyfuscractive. Srmnery o Embedded C++ is a Cr+ yeniion, which makes largs Fogram development simpler by providing object orientodprrognmming feahres of usingan object,which bitds stat and behaviorand which is dcfind by an instrnceof a chss. o Diab oompihr has two spccial festurs - processor specificcodeopimizdion andrun tirne analysis tools for finding expected runtime errors.


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(scalardatatypes) in place of the objects (referencedatatypes)as argumentsand use local variables asmuchas 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 featuresprovided in C+r. . EmbeddedC++ is a versionof C+r that provides for a selectivedisablingof the abovefeaturesso that there is a lessruntime overhead and lessruntime library. . The solutions for the library functions in an embedded C#t compiler are alsoreentrant. . 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 extensiveuse in the C++ environment in embedded software development.



A compilergenerates an objectfile. The objectfile is generated program on compilation while an executable file is.required, whichhasthe source having codes theabsolute addresses.. g For compilationfor.the hostalone,the compilercanbe turboC. TurboC# or8orland C andBorlandC++.


SYste$ Embodded , Onecompileris-for $e host . Two *rnpit"ot " needed' and designand *'tti"tt doesthc devolopment cor-nputer compileris a second The debugging: ' "ft"iftt t"Jingcr{ cross-comPiler. r There is a popular freeware calhd GNU CIC++ for 68HCl1' "Apiftt andffi Asl lM assembler both as hostcompiler , ' , A GNU compileris configurable 80x86' Window supports 'as well ss cro$'Gornpiler':It 95/NT, 80xS6 Red Hat Linux and scveral other platforms. ' It supports80x86, 68HCll, 80960' PowerPCand processors' ' system othertargBt several

3.8.f Crcss ComPiler the The cross compiler runs on a host machine'but develops embedded of the ( Processor codesio, u tt g"tedsystem machine and simuiate emulate can system that ; target system).It means on the host system tire application . T h e ta rg e tsy$ e m.sp e cificor m ultiple.choicecr oss. maybe used' areonuilubttcommercially compitersttrai . These are available for most enrbpddodsystem TheIAR System' andmiorocontrollers' microprocesqpn for manytargets' Swedin,offerscross-compilers .ThetargetscarrbeofthePfarrrilyorS05lfamily, familY' or 80196 68HClf famitY ' FCM is another closs compiler for the PIC (hogrammable Intemrpt Controller) microcortroller hostalsoruns l6F876.The or l6-C76, i*''ty, PIc 16F84 thecross-compilcrthatoffersanintcgrateddevelopment envincnment Erecutablc File Inanembeddedsystemdesig&asthefinalstep'thebytes.mustbe 'C' prognm helps to olacedat thc ROM after irnpildiom' A

and EmHded Prcgra4ming 3.25 Concepts Procrammine .program vectors, tables, uscsto put (storeor buri data'constants, ROM in the codes andttresource and-strings, allocationto A locatorfile hasthe final informdion of memory thenuses Thi locator so on. data and datainitialization the codes, the source codewithin the map file. andgenerafes the allopation addresses. allocated : TheROM hasthe followingsections: . Machine (Execrrtable) codesfor the bootshap(rcse0 program .. . Initialization(default)dataat shadow ROM for copying into the RAM duringexecution . Codes routines service and.intemrpt for the application . System the br the execution dataneeded configuration codes o Standard andtables dataor vectors . Machine codes for the device and device drivers Summary in is essential andcrosscompilers compilers Useof appropriate development software anyembedded


tool is of greathelp for source-code codeengineering A source developmen!compiling and cross compiling.The tools are C/C+r code enginecring, commerciallyavailablefor embedded anddebugging. testing navigation The featuresof a typical tool are comprehension, (disabling and and browsing editing debugging configuring A tool for C andC+| is SNiFF+.It is the C+r features). enabling

ffit""; ;hJr*i

nr. .*crutabl"filc is tlrefile thata device



8rd E nbdded Pnogramndm 327 Concepts Proerammins

frotn WirdRirct Sysuns. A vcrsionSNiFF+PROcodeas well ofthe tool areasfollows: module.Mrin fcaturcs asdebug It seschasand li$s thc definilions' symbols'hierarchy tslcs andchss inhritsnoc of theclasscs, of symbolsand and liss ilre dependcncios It searches (mcfiods) and ftnrctiors variablcs, dcfincd symbols, othcrsymbols. It mqritors' cnabhs and tlrc implcrnentatiolt Yirtualfrmctions. It fu& dtGftll cftct of ur.yco& dtdtge on dtc soume codc. ft scsshcsdd lists trc dcpcn&nciesmd hicrarchyof irchdod hcldcr fihs. and !t navigScsto ard fio barrccn thc imphrnentation synrboldech*ion ft navigUesto and Ao bctwoentlrc ovcrridden and overriding nrethods. [Overridingme0rodis metlrodin daugbtcrihss with samenamcard srmc numberand as in the pastt class.Overriddcn types of arguments ithttoO is tlre rtthod of thc porcntchss, which has olas. becnFdfinod*the daugfttcr It browscsfftrou$ informationrcgnrdinginstantiation of a chss. (objoctcreation) ft browscs ftturgh information encapsulationof andbrswscsthroughthe amongthe mernbers variables visibility of ttremembers' public,privateandprotected
o a a

Snmmaty applications softrraredesignerfor sophisticated The embeddcd coding,profiling, tool for program a soure codeengineering uses system softrrare. of embedded testinganddebugging



and fi1tedin smallmemoryaf,eas Whencodesare madccompact performance, it is called memoty without affecting the codo of CPU cycles,and It alsoreduces the total number optimization. thuq thetotal enerryrequircments. the useof memoryin a for optimizing Thefollowingareused system. hyte Usedeclarotbn os unsigned 0 and If thereis a variable,which alwayshasa valuebetween 255. When using data sfuctures,limit the maximumsize of queues, lists and stackssize to 256. Byte arithmetictakes less time thanintegerarithmetic. wsigned bytes Foltow a rule thot uses for a short ond a short imeger an for It is usedto optimizeuseof the RAM and ROM availablein the use of 'long' integersand the system.Avoid if possible 'double'precision pointvalues. floating of librarylundtons if a simplercodingis possibla Avoid use Library functions arp the generalfunctions.Use of general Follow a rule that cases. mormemoryin several fuirctionneeds function is avoidsuseof library functionsin casea generalized is when its coding simple. to takemorememory expocted

relatiorrships' objectcomportent through It browses tasks' enor- proneandunused rcmoves It automatically andreplacement' search easyandautomated It provides

.. andEmbeddedProgamming ProprammineConcepts !.29

s4 or lenows fully the instruction ffi"er beused must codes assimbty thetargetptocessor,
devicedriver This alsoallowstheefficientuseof mem-ary.The oro**rinassemblyespeciallyprovideeffrciencyduetothe for the controlandstatus Uit r"ir.."t instructions ;;Hil;tne .*gi't'*o"lythefewassemblycodesforusingthedevice.V0 are nee&d. The best confiol and statusregisters ffi addressei, for the given applications' lt" it made of availablefeatures A coding also helpsin codingfor atomicoperations' ;;;Uy to access a modifierregistercanbe usedin the C progam for-fast it is tequentlyemployed' portA Oata It"Or*ifV is"O nutiaUle.If The 'register portAfall" unsignedbye is used as follows, to place portAdatain a compiier register directs'the ;J.'* of theprocessor' register general-purpose

As long as sharcd dota problem does orise, the ase of global variables can be optimired. Theseare not used as the argumentsfor passingthe values. A good function is one that has argumentsto be passed.The passed values are saved on'the stacksin 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 overheadsin the function call and return.But this is at the cost of the codesfor eliminating shared data problem. When a variable is declared with less instruction than from the statiq, the processoraccesses stack. As a rule, use global variables if shared data problem are tackled and use static variablesin caseit needssaving frequently on the stack.

Asa ru l e ,u se th e a sse mblycodesfor sim plefunctionslike and bit Combine two functions if possible. As a rule, whenever ,onngoting the device tontroi register,port addresses Use feasiblecombinetwo functionsof more of lesssimilar codes. Gt is clearly understood' if the instruction ;;dilt6ns and increment for . Bringing the tasksinto an initiated task list will reduce codes for the atomic operations |,[ffit variable' used frequently a for register the fr,equent interactions with the OS and context uJAiti#Ut modifier on a memttrystackand Cating afunction carrsr contert saving on retirn the cont& is retrieved' Thisinvolvestimeandcanincreasetheworst.caseintemrpt. modifieris latcncy.Therei, n,Jiner inline. when the inline when places at all the codes theactual ;r.4lh. oompilerinserts theseoperatoo*_o*d.Thisreducesthetimeands taclt at thecosto oulir,"ui, in the functioncall andretum.But"this is forthe codes' moreROM beingneeded the size of the prograT but gives r If used,it increases usini tne modifier directsthe compilerto put th, faster speed. tha' flt tr," n nition (in curlv u9:"t) instel! -of calling ;;; frequentlyuse n n"tion. As a rule, use inline modifiersfor all overloadin ,r"ii *t, of codesin trr" function or the operator A vacantROI\ functionsif trrenoM is availablein the system' Why not useit for reducingth resource' memoryis an unused i rnt ^rpi-iutencies by eliminatingthe time taken worst-case context? andietrievalof a program fr"quJ;e
savings and retrievals stack and time overheads. Optimize the RAM use for the stacks. It is done by reducingthe numberof tasksthat interactwith 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 optimizesthe use of the stack. As a rule reduce use of frequent function calls and nested calls and thus reduce the time and RAM respectively. for the stacks, memory needed r Use if feasible, alternativesto the switch statements with a table of pointers to the functions. This saves to processortime in deciding which set of statements executewhile performingthe conditionaltestsall down a chain.

o Use the deletefunction when there is no longer a need for a set of statementsafter that execute. As a rule, to

frethe RAM used by a sctof sta0crrasausethe detete functionanddestructor functions. . When using C++, configure thc compilcr for not permittingthe muhi-inhcritance, bmplaleq exccptional handlirry; rrcw g1ile castsr virtuEl basc classei, ard namcspe$. As r nrle, for usingCr+, usc the classes without muhiple inheritance,without template,with nrntimeidentification andwith throwable occeptions. Sumnery Embedded software d$igners mustusvariousstandard waysfor optimizing thememory needs in a system.