1、Chapter 25 Embedded systems programming,Bjarne S lecture provides a brief overview of what distinguishes embedded systems programming from “ordinary programming.” It then touches upon facilities that become prominent or problems when working “close to the hardware” such as free store use, bit manipu
2、lation, and coding standards. Remember: not all computers are little grey boxes hiding under desks in offices.,2,Stroustrup/Programming Nov13,Overview,Embedded systems Whats special/different predictability Resource management memory Access to hardware Absolute addresses Bits unsigned Coding standar
3、ds,3,Stroustrup/Programming Nov13,Embedded systems,Hard real time Response must occur before the deadline Soft real time Response should occur before the deadline most of the time Often there are plenty of resources to handle the common cases But crises happen and must be handled Predictability is k
4、ey Correctness is even more important than usual “correctness” is not an abstract concept “but I assumed that the hardware worked correctly” is no excuse Over a long time and over a large range of conditions, it simply doesnt,4,Stroustrup/Programming Nov13,Embedded systems,Computers used as part of
5、a larger system That usually doesnt look like a computer That usually controls physical devices Often reliability is critical “Critical” as in “if the system fails someone might die” Often resources (memory, processor capacity) are limited Often real-time response is essential,5,Stroustrup/Programmi
6、ng Nov13,Embedded systems,What are we talking about? Assembly line quality monitors Bar code readers Bread machines Cameras Car assembly robots Cell phones Centrifuge controllers CD players Disk drive controllers “Smart card” processors,6,Fuel injector controls Medical equipment monitors PDAs Printe
7、r controllers Sound systems Rice cookers Telephone switches Water pump controllers Welding machines Windmills Wrist watches ,Stroustrup/Programming Nov13,Do You Need to Know This Stuff ?,Computer Engineers You will build and oversee the building of these systems All “close to the hardware” code rese
8、mbles this The concern for correctness and predictability of embedded systems code is simply a more critical form of what we want for all code Electrical Engineers You will build and oversee the building of these systems. You have to work with the computer guys You have to be able to talk to them Yo
9、u may have to teach them You may have to take over for them Computer scientists youll know how to do this or only work on web applications (and the like),7,Stroustrup/Programming Nov13,Predictability,C+ operations execute in constant, measurable time E.g., you can simply measure the time for an add
10、operation or a virtual function call and thatll be the cost of every such add operation and every virtual function call (pipelining, caching, implicit concurrency makes this somewhat trickier on some modern processors) With the exception of: Free store allocation (new) Exception throw So throw and n
11、ew are typically banned in hard real-time applications Today, I wouldnt fly in a plane that used those In 5 years, well have solved the problem for throw Each individual throw is predictable Not just in C+ programs Similar operations in other languages are similarly avoided,8,Stroustrup/Programming
12、Nov13,Ideals/aims,Given the constraints Keep the highest level of abstraction Dont write glorified assembler code Represent your ideas directly in code As always, try to write the clearest, cleanest, most maintainable code Dont optimize until you have to People far too often optimize prematurely Joh
13、n Bentleys rules for optimization First law: Dont do it Second law (for experts only): Dont do it yet,9,Stroustrup/Programming Nov13,Embedded systems programming,You (usually) have to be much more aware of the resources consumed in embedded systems programming than you have to in “ordinary” programs
14、 Time Space Communication channels Files ROM (Read-Only Memory) Flash memory You must take the time to learn about the way your language features are implemented for a particular platform Hardware Operating system Libraries,10,Stroustrup/Programming Nov13,Embedded systems programming,A lot of this k
15、ind of programming is Looking at specialized features of an RTOS (Real Time Operating System) Using a “Non-hosted environment” (thats one way of saying “a language right on top of hardware without an operating system”) Involving (sometimes complex) device driver architectures Dealing directly with h
16、ardware device interfaces We wont go into details here Thats what specific courses and manuals are for,11,Stroustrup/Programming Nov13,How to live without new,Whats the problem? C+ code refers directly to memory Once allocated, an object cannot be moved (or can it?) Allocation delays The effort need
17、ed to find a new free chunk of memory of a given size depends on what has already been allocated Fragmentation If you have a “hole” (free space) of size N and you allocate an object of size M where MN in it, you now have a fragment of size N-M to deal with After a while, such fragments constitute mu
18、ch of the memory,12,Free space,New object,old object,old object,Stroustrup/Programming Nov13,How to live without new,Solution: pre-allocate Global objects Allocated at startup time Sets aside a fixed amount of memory Stacks Grow and shrink only at the top No fragmentation Constant time operations Po
19、ols of fixed sized objects We can allocate and deallocate in any order No fragmentation Constant time operations,13,Pool:,Stack:,Top of stack,Stroustrup/Programming Nov13,How to live without new,No new (of course) And no malloc() (memory allocation during runtime) either (for those of you who speak
20、C) No standard library containers (they use free store indirectly) Unless you have a special hard-real time implementation Instead Define (or borrow) fixed-sized Pools Define (or borrow) fixed-sized Stacks Do not regress to using arrays and lots of pointers,14,Stroustrup/Programming Nov13,Pool examp
21、le,/ Note: element type known at compile time / allocation times are completely predictable (and short) / the user has to pre-calculate the maximum number of elements needed template class Pool public:Pool(); / make pool of N Ts construct pools only during startupT* get(); / get a T from the pool; r
22、eturn 0 if no free Tsvoid free(T* p); / return a T given out by get() to the pool private:/ keep track of TN array (e.g., a list of free objects) ;Pool sb_pool; Pool indicator_pool;,15,Stroustrup/Programming Nov13,Stack example,/ Note: allocation times completely predictable (and short) / the user h
23、as to pre-calculate the maximum number of elements needed template class Stack public:Stack(); / make an N byte stack construct stacks only during startupvoid* get(int N); / allocate n bytes from the stack; return 0 if no free spacevoid free(void* p); / return the last block returned by get() to the
24、 stack private:/ keep track of an array of N bytes (e.g. a top of stack pointer) ;Stack my_free_store; / 50K worth of storage to be used as a stackvoid* pv1 = my_free_store.get(256 * sizeof(int); / allocate array of ints int* pi = static_cast(pv1); / you have to convert memory to objectsvoid* pv2 =
25、my_free_store.get(50); Pump_driver* pdriver = static_cast(pv2);,16,Stroustrup/Programming Nov13,Templates,Excellent for embedded systems work No runtime overhead for inline operations Sometimes performance matters No memory used for unused operations In embedded systems memory is often critical (lim
26、ited),17,Stroustrup/Programming Nov13,How to live with failing hardware,Failing how? In general, we cannot know In practice, we can assume that some kinds of errors are more common than others But sometimes a memory bit just decides to change (cosmic ray, silicon fatigue, ) Why? Power surges/failure
27、 The connector vibrated out of its socket Falling debris Falling computer X-rays Transient errors are the worst E.g., only when the temperature exceeds 100 F. and the cabinet door is closed Errors that occur away from the lab are the worst E.g., on Mars,18,Stroustrup/Programming Nov13,How to live wi
28、th failing hardware,Replicate In emergency, use a spare Self-check Know when the program (or hardware) is misbehaving Have a quick way out of misbehaving code Make systems modular Have some other module, computer, part of the system responsible for serious errors In the end, maybe a person i.e., man
29、ual override Remember HAL ? Monitor (sub)systems In case they cant/dont notice problems themselves,19,Stroustrup/Programming Nov13,Absolute addresses,Physical resources (e.g., control registers for external devices) and their most basic software controls typically exist at specific addresses in a lo
30、w-level system (e.g., memory-mapped I/O) We have to enter such addresses into our programs and give a type to such data For example Device_driver* p= reinterpret_cast(0xffb8); Serial_port_base* Com1= reinterpret_cast(0x3f8);,20,Stroustrup/Programming Nov13,Bit manipulation: Unsigned integers,How do
31、you represent a set of bits in C+? unsigned char uc; / 8 bits unsigned short us; / typically 16 bits unsigned int ui; / typically 16 bits or 32 bits / (check before using) / many embedded systems have 16-bit ints unsigned long int ul; / typically 32 bits or 64 bits std:vector vb(93); / 93 bits true/
32、false auto-converts to/from 1/0 Use only if you really need more than 32 bits std:bitset bs(314); / 314 bits Use if you really need more than 32 bits Typically efficient for multiples of sizeof(int),21,Stroustrup/Programming Nov13,Bit manipulation,& and | inclusive or exclusive or right shift ones c
33、omplement,22,0,1,0,0,1,0,1,1,0xaa,0,0,0,1,1,1,1,0,0x0f,0,0,0,0,1,0,1,0,0x0a,a:,a&b:,b:,0,0,0,1,1,0,0,0,0x03,b2:,1,1,1,0,0,0,0,1,0xf0,b:,0,1,0,1,1,1,1,1,0xaf,a|b:,0,1,0,1,0,1,0,1,0xa5,ab:,1,0,1,0,0,1,0,0,0x54,a1:,Stroustrup/Programming Nov13,Bit manipulation,Bitwise operations/ sign bit (if 2s comple
34、ment)/ ,23,1,1,0,0,1,0,1,0,1,1,0,0,1,1,0,Sign bit,1,1,1,1,1,1,1,1,0xff:,8 bits = 1 byte,0,1,0,0,1,0,val,0,1,1,false,true,Stroustrup/Programming Nov13,Bit manipulation,Or | Set a bit (whether or not already set) And / the cast is necessary because the compiler/ doesnt know that 5 is in the Flags rang
35、e,24,1,1,1,1,1,1,1,1,0xff:,0,1,1,1,1,val,0,0,0,Stroustrup/Programming Nov13,Bit manipulation,Exclusive or (xor) ab means (a|b) Immensely important in graphics and cryptography,25,0,1,0,0,1,0,1,1,0xaa,0,0,0,1,1,1,1,0,0x0f,0,1,0,1,0,1,0,1,0xa5,a:,ab:,b:,Stroustrup/Programming Nov13,Unsigned integers,Y
36、ou can do ordinary arithmetic on unsigned integers Avoid that when you can Try never to use unsigned just to get another bit of precision If you need one extra bit, soon, youll need another Dont mix signed and unsigned in an expression int x = -2;/ a negative number unsigned int y = x;/ a very large
37、 positive number if (x 1) cout “no surprise: x1n“; if (y 1) cout “y1n“; else cout “surprise? not y1n“; if (-3 x) cout “no surprise: -3xn“; if (-3 y) cout “surprise? -3yn“; if (3 y) cout “surprise? 3yn“;,26,Stroustrup/Programming Nov13,Unsigned integers,You can do ordinary arithmetic on unsigned inte
38、gers You cant completely avoid unsigned arithmetic Indexing into standard library containers uses unsigned (in my opinion, thats a design error; arrays use signed ints) vector v; / for (int i = 0; i:size_type i = 0; i:iterator p = v.begin(); p!=v.end(); +p) for (auto p = v.begin(); p!=v.end(); +p) f
39、or (auto i = 0; iv.size(); +i) for (int x : v) ,27,unsigned,correct, but pedantic,Yet another C+11 way,Stroustrup/Programming Nov13,signed,A C+11 way,signed,Complexity,One source of errors is complicated problems Inherent complexity Another source of errors is poorly-written code Incidental complexi
40、ty Reasons for unnecessarily complicated code Overly clever programmers Who use features they dont understand Undereducated programmers Who dont use the most appropriate features Large variations in programming style,28,Stroustrup/Programming Nov13,Coding standards,A coding standard is a set of rule
41、s for what code should look like Typically specifying naming and indentation rules E.g., use “Stroustrup” layout Typically specifying a subset of a language E.g., dont use new or throw (to avoid predictability problems) Typically specifying rules for commenting Every function must have a comment exp
42、laining what it does Often requiring the use of certain libraries E.g., use rather than to avoid safety problems Organizations often try to manage complexity through coding standards Often they fail and create more complexity than they manage,29,Stroustrup/Programming Nov13,Coding standards,A good c
43、oding standard is better than no standard I wouldnt start a major (multi-person, multi-year) industrial project without one A poor coding standard can be worse than no standard C+ coding standards that restrict programming to something like the C subset do harm They are not uncommon All coding stand
44、ards are disliked by programmers Even the good ones All programmers want to write their code exactly their own way A good coding standard is prescriptive as well as restrictive “Here is a good way of doing things” as well as “Never do this” A good coding standard gives rationales for its rules And e
45、xamples,30,Stroustrup/Programming Nov13,Coding standards,Common aims Reliability Portability Maintainability Testability Reusability Extensibility Readability,31,Stroustrup/Programming Nov13,Some sample rules,No function shall have more than 200 lines (30 would be even better) that is, 200 non-comme
46、nt source lines Each new statement starts on a new line E.g., int a = 7; x = a+7; f(x,9); / violation! No macros shall be used except for source control using #ifdef and #ifndef Identifiers should be given descriptive names May contain common abbreviations and acronyms When used conventionally, x, y
47、, i, j, etc., are descriptive Use the number_of_elements style rather than the numberOfElements style Type names and constants start with a capital letter E.g., Device_driver and Buffer_pool Identifiers shall not differ only by case E.g., Head and head / violation!,32,Stroustrup/Programming Nov13,So
48、me more sample rules,Identifiers in an inner scope should not be identical to identifiers in an outer scope E.g., int var = 9; int var = 7; +var; / violation: var hides var Declarations shall be declared in the smallest possible scope Variables shall be initialized E.g., int var; / violation: var is
49、 not initialized Casts should be used only when essential Code should not depend on precedence rules below the level of arithmetic expressions E.g., x = a*b+c; / ok if( ab | c=d) / violation: parenthesize (ab) and (c=d) Increment and decrement operations shall not be used as subexpressions E.g., int x = v+i; / violation (that increment might be overlooked),
copyright@ 2008-2019 麦多课文库(www.mydoc123.com)网站版权所有
备案/许可证编号:苏ICP备17064731号-1