Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more ➡
Download
Standard view
Full view
of .
Add note
Save to My Library
Sync to mobile
Look up keyword
Like this
76Activity
×
0 of .
Results for:
No results containing your search query
P. 1
C Programming for Embedded Systems

C Programming for Embedded Systems

Ratings:

4.67

(3)
|Views: 10,029|Likes:
Published by sgganesh
see www.joyofprogramming.com
see www.joyofprogramming.com

More info:

Published by: sgganesh on Jun 02, 2009
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See More
See less

02/07/2013

pdf

text

original

 
Overview
September 2008
|
LINUX For YoU
|
 www.nItis.c
72
Even if C is losing its position as the mainstream programming language for general application development, embedded programming is still its strong-hold. Students and programmers new to embedded programming, though
procient in general C programming, are often clueless about C programming
for embedded systems. This article offers an introduction.
 very embedded system hassotware and hardware elementsthat are very closely dependent,and this aects how we programan embedded device. Basedon this act, we’ll look at the hardwarecharacteristics o embedded devices, how thehardware aects the language chosen to writeprograms or it, how C is used dierentlyor embedded programming and, nally,we’ll cover how GCC is used or embeddedsystems.
Characteristics of embedded devices
Programming or embedded systems isquite dierent rom general programming(or PCs). The main dierence is due tothe underlying hardware. The importantcharacteristics o embedded systems whencompared to regular PCs are:Embedded devices have signicantresource constraints; typically, lessmemory, less processing power andlimited hardware devices compared toregular desktop computers. [But this isslowly changing; the latest embeddeddevices have considerably more resources(such as a huge memory) and are morepowerul than ever beore. Nowadays,with smart mobile phones, we can
 P r o g r a m m i n g  f o r  E m b e d d e d  S y s t e m s
E
 
Overview
www.nItis.c
|
LINUX For YoU
|
September 2008
73
browse the Internet, play games, make phone calls,and even do programming—so, handheld devices arebecoming as powerul as a PC, blurring the dierencebetween embedded systems programming and generalprogramming.]The hardware components used are not the same as theones used or a PC: the components in an embeddeddevice are lighter, cooler, smaller and less power-consuming. To be specic, the processor used in anembedded system is rarely the same used in a PC; andheavy I/O devices such as keyboards and monitors arenot used in embedded systems.Embedded systems are more tied to the hardware/OS vendor than the PCs. PCs are general-purpose machinesand we can take the availability o applications andprogramming tools or granted. However, embeddedsystems are typically more tied to the hardware or OS vendor and, hence, the common applications or tool-chains need not be widely or reely available.Embedded systems should be more reliable andecient. I a program in a PC ails, we can restart theprogram and nothing serious happens. However, ormany embedded system programs, i they ail, theycan make the device useless. And sometimes they cancause serious harm -- imagine what could happen i anembedded program in a pacemaker device ails.
Programming for embedded devices
 An embedded hardware device, depending on its sizeand capabilities, can have an operating system—such asembedded Linux—with limited or minimal unctionalitycompared to a desktop version. For very small embeddeddevices, an OS might be entirely absent: it is not possible towrite programs, compile, run and debug the code in suchsmall devices. In such a situation, it is necessary to usecross compilers (or assemblers), which compile programswritten in a high-level language on a host system (typicallya PC) and generate code or a target system (or example,an embedded device). I we write assembly programs anduse an assembler running on a host to generate code ora target device, it is a cross assembler. So, we can writeprograms on our PC, generate code or the embeddeddevice and run it there. This solves the problem o creatingexecutable code or embedded systems, but testing,debugging or tracing embedded programs is dicult.One problem is that these programs usually don’t haveinput devices such as keyboards and a mouse, or outputdevices like ull-fedged monitors or display screens that weusually take or granted in regular programming or PCs. So,debugging, xing and testing them is oten more dicult.Fortunately, there are tools available to help an embeddedprogrammer. For example, an in-circuit emulator is ahardware device used to help debug the program that runsin an embedded system. It plugs on top o an embeddeddevice; it can be even used to emulate a processor that is yet to be developed! With help rom this device, we canset breakpoints, visualise the processing o the embeddedhardware or monitor the signals in the pins. In this way,it is possible to debug programs, though it is not asconvenient as regular debugging. There are also other aidssuch as simulators. For those new to embedded systems,understanding such domain-specic details takes more timethan actually writing the programs.
Languages for programming embedded devices
C is the language o choice or most o the programmingdone or embedded systems. Why? Why not assemblylanguage, C++, Java or any other language?It might appear that assembly language is intuitivelythe most obvious choice, since embedded programming isall about programming hardware devices such as micro-controllers. It is true that micro-controllers were initiallyprogrammed mostly in assembly language as with otherembedded devices. It is not that dicult to write anassembly program since the assembly language producesthe tightest code, making it possible to squeeze everypossible byte o memory usage. However, the problem isthat it becomes dicult to use or any reasonably-sizedprogram, and even a slightly complicated device. Thediculties are in getting assembly programs to workcorrectly; and understanding, debugging, testing and,most importantly, maintaining them in the long run. Also,high quality C compilers can oten generate code that iscomparable to the speed o programs written in assembly.So, the benets o using assembly or eciency arenegligible compared to the ease with which programmerscan write C code. However, i perormance is the key tomake or break a device, then it is hard to beat assembly. Forexample, DSP (digital signal processing) devices are mostlyprogrammed in assembly even today, because perormanceis the most important requirement in these devices.Languages such as C++ have eatures that are otenbulky, inecient or inappropriate or use in resource-constrained environments such as embedded devices. Inparticular, virtual unctions and exception handling aretwo language eatures that are not ecient in terms o space and speed in embedded systems. Sometimes, C++programming is used as ‘Sae C’, where only a small subseto C++ eatures is included. However, or convenience, mostembedded projects pragmatically use C itsel.Languages with ‘managed runtimes’, such as Java, aremostly heavyweight. Running Java programs requires aJava Virtual Machine, which can take up a lot o resources.Though Java is popular in high-end mobile phones becauseo the portability it provides and or browsing the Web, it israrely suitable or use in small embedded devices.There are numerous special purpose or proprietarylanguages meant to be used in embedded systems suchas B# and Dynamic C. Others, like Forth, are also wellsuited or the purpose. However, C is widely used andamiliar to programmers worldwide, and its tools areeasily available.
 
Overview
September 2008
|
LINUX For YoU
|
 www.nItis.c
74
How C is used differently for embeddedprogramming
I you are new to embedded C programming, you will noticethat there are only subtle dierences between a regular Cprogram and an embedded C program.The ollowing is a list o the most important dierencesbetween C programming or embedded systems and Cprogramming or PCs.
Writing low-level code
: In embedded programming, itis necessary to directly access the underlying hardware.For example, we might need to access a port, timeror a memory location. Similarly, we might need to dolow-level programming activities like accessing the jobqueue, raise some signals, interrupts, etc. So, we needto write low-level programs that directly access, modiyor update hardware; this is an important characteristico embedded C programs. How do we write low-levelcode? C eatures such as pointers and bit-manipulationacilities enable us to program at the hardware leveldirectly; so these eatures are used extensively inembedded programming.
Writing in-line assembly code
: The C languageprovides a limited set o eatures, so it is not possibleto use high-level C code to perorm a specic unction.For example, the device might have some instructionsor which there is no direct equivalent in C code (orexample, bit-wise rotation). In such cases, we can writeassembly code embedded within C programs called‘inline assembly’. The exact syntax depends on thecompiler; here is an example or GCC:
inta=10,b;asm(“movl%1,%%eax;movl%%eax,%0;”:”=r”(b)/*output*/:”r”(a)/*input*/:”%eax”/*clobberedregister*/);
This code just assigns a to b (!), but this is just anexample to show how in-line assembly code looks; usuallyit will have the
asm
keyword prexed and/or suxed byunderscores. The assembly code is written in C programitsel and we can use C variables to reer to data; theregister allocation and other details will be taken care o bythe compiler. We can write high-level unctionality such aslooping in C syntax, and only when we require processorspecic unctionality, we can write in-line assembly code. Inthis way, writing in-line assembly is more convenient thanwriting ull-fedged assembly code.
 No recursion, no heap:
Many o the devices are small,so the heap area (where dynamic memory segments willbe allocated) might be limited or might not even exist.So, we would need to program without using
 malloc
or its variations. This poses diculties or those newto embedded systems: how to use a linked list or a tree
data structure which we conventionally program usingdynamic memory allocation?Fortunately, many o the data structures can beimplemented by using static allocation itsel. Here is asimple illustration o a doubly linked list made up o threenodes that are allocated statically (instead o dynamicmemory allocation):
structnode{structnode*prev;intdata;structnode*next;};intmain(){structnodeone,two,three;one.prev=&three;one.next=&two;one.data=100;two.prev=&one;two.next=&three;two.data=200;three.prev=&two;three.next=&one;three.data=300;structnode*temp=&one;do{printf(%d,temp->data);temp=temp->next;}while(temp!=&one);}
This program prints ‘100 200 300’. Using the basicidea rom this program, i we pre-allocate the numbero expected nodes statically, then we can write our own
 my_node_malloc()
unction that will return a node thatwas allocated statically. Using such techniques, it is possibleto implement dynamic data structures such as linked listsand trees that still work under the limitations o embeddeddevices.Similarly, eatures such as recursion are not allowedin most o the embedded devices. One reason is that therecursion is inecient in terms o space and time comparedto iterative code. Fortunately, it is possible to writeany recursive code as iterative code (though writing orunderstanding iterative versions o the code is not usuallyintuitive).To put it simply, costly language eatures (in terms o space and time) are either not available, nor recommendedin embedded programming. As programmers, we shouldnd alternative ways o achieving the same unctionality.
Using limited C features or new languageextensions
: Some o the language eatures that we takeor granted in regular programming might simply notbe available or embedded programming. For example,i the device does not support foating point numbers,then we cannot use foats or doubles in the programs.Problems requently occur the other way also: oten,the underlying devices have hardware eatures that don’thave direct support in the C programming language. Forexample, a device might support xed-point numbers;however, C language doesn’t have any support or this data

Activity (76)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
achuu1987 liked this
Aicha Eugene liked this
Malu Mohan liked this
asdjjgghhjj liked this
monajosephjustin liked this
ibotchak liked this
Andrei Dulea liked this

You're Reading a Free Preview

Download
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->