C for Microcontrollers Just Being Efficient Lloyd Moore
‘C’ for Microcontrollers, Just Being Efficient Lloyd Moore, President Lloyd@Cyber. Data-Robotics. com www. Cyber. Data-Robotics. com
Agenda l Microcontroller Resources l Knowing Your Environment l Memory Usage l Code Structure l Interrupts l Math Tricks l Optimization
Disclaimer Some microcontroller techniques necessarily need to trade one benefit for another – typically lower resource usage for maintainability l Point of this presentation is to point out various techniques that can be used as needed l Use these suggestions when necessary l Feel free to suggest better solutions as we go along l
Microcontroller Resources EVERYTHING resides on one die inside one package: RAM, Flash, Processor, I/O l Cost is a MAJOR design consideration l l Typical costs are $0. 25 to $25 each (1000’s) RAM: 16 BYTES to 32 K Bytes typical l Flash/ROM: 384 BYTES to 256 K Bytes l Clock Speed: 4 MHz to 80 MHz typical l Much lower for battery saving modes (32 KHz) Bus is 8, 16, or 32 bits wide (just like the old days)
Other Considerations l Specialized resources often present l l Portability inside families a big concern l l May have hardware centric API, or just raw registers! No floating point hardware l l Across families, not so much Typically no operating system present l l Counters, UART, USB PHY, LCD Controller May have other math hardware (MAC, CRC) No protected memory / MMU l Do have specialized memory segments
Power Consumption l Microcontrollers typically used in battery operated devices l Power requirements can be EXTREMELY tight Energy harvesting applications l Long term battery installations (remote controls, hard to reach devices, etc. ) l l EVERY instruction executed consumes power, even if you have the time!
Know Your Environment l Traditionally we ignore hardware details l Need to tailor code to hardware available l Specialized hardware MUCH more efficient l Compilers typically have extensions Interrupt – specifies code as being ISR l Memory model – may handle banked memory and/or simultaneous access banks l Multiple data pointers / address generators l l Debugger may use some resources
Memory Usage l l Use ‘const’ to put data into program memory Alignment / padding issues l l Avoid dynamic memory allocation l l l Take extra space and processing time Memory fragmentation a big issue Use and reuse static buffers l l Typically NOT an issue, non-aligned access ok Reduces variable passing overhead Allows for smaller / faster code due to reduced indirections Does bring back over write bugs if not done carefully Use the appropriate variable type l l Don’t use int and double for everything!! Affects processing time as well as storage
Char vs. Int Increment on 8051 char c. X; c. X++; 000 A 000 D 000 E 000 F l l 900000 E 0 04 F 0 MOVX INC MOVX DPTR, #c. X A, @DPTR A @DPTR, A 6 Bytes of Flash 4 Instruction cycles int i. X; i. X++; 0000 0003 0004 0007 900000 E 4 75 F 001 120000 MOV CLR MOV LCALL DPTR, #i. X A B, #01 H ? C? IILDX 10 Bytes of Flash + subroutine overhead l Many more than 4 instruction cycles with a LCALL l
Code Structure l Count down instead of up l l l Pointers vs. array notation l l Saves a subtraction on all processors DJNZ style instruction on some processors Generally better using pointers Bit Shifting l l l May not always generate what you think May or may not have barrel shifter hardware May or may not have logical vs. arithmetic shifts
Shifting Example c. X = c. X << 3; 0006 0007 0008 0009 l l l 33 33 33 54 F 8 c. A = 3; c. X = c. X << c. A; RLC RLC ANL A A, #0 F 8 H Constants turn into seperate statements Variables turn into loops Both of these can be one instruction with a barrel shifter 000 B 000 E 000 F 0010 0011 0013 0014 0016 0017 0018 900000 E 0 FE EF A 806 08 8002 C 3 33 D 8 FC MOV DPTR, #c. A MOVX A, @DPTR MOV R 6, A MOV A, R 7 MOV R 0, AR 6 INC R 0 SJMP ? C 0005 ? C 0004: CLR C RLC A ? C 0005 DJNZ R 0, ? C 0004
More Code Structure l Actual parameters typically passed in registers if available l l Global variables l l Keep function parameters to less than 3 May also be passed on stack or special parameter area May be more efficient to pass pointer to struct While generally frowned upon for most code can be very helpful here Typically ends up being a direct access Read assembly code for critical areas Know which optimizations are present l l Small compilers do not always have common optimizations Inline, loop unrolling, loop invariant, pointer conversion
Indexed Array vs Pointer on M 8 C uc. Mode = g_Channels[uc_Channel]. uc. Mode; 01 DC 01 DE 01 E 0 01 E 2 01 E 3 01 E 5 01 E 6 01 E 8 01 E 9 01 EB 01 EC 01 EF 01 F 1 01 F 4 01 F 7 01 FA 01 FD 01 FF 52 FC 5300 5000 08 5100 08 5007 08 7 C 0000 38 FC 5 F 0000 060000 0 E 0000 3 E 00 5403 mov A, [X-4] mov [__r 1], A mov A, 0 push A mov A, [__r 1] push A mov A, 0 push A mov A, 7 push A xcall __mul 16 add SP, -4 mov [__r 1], [__r. X] mov [__r 0], [__r. Y] add[__r 1], <_ g_Channels adc[__r 0], >_ g_Channels mvi A, [__r 1] mov [X+3], A uc. Mode = p. Channel->uc. Mode; 01 ED 01 EF 01 F 1 01 F 3 l l 5201 5300 3 E 00 5405 mov mvi mov A, [X+1] [__r 1], A A, [__r 1] [X+5], A Does the same thing Saves 29 bytes of memory AND a call to a 16 bit multiplication routine! Pointer version will be at least 4 x faster to execute as well, maybe 10 x Most compilers not this bad – but you do find some!
Interrupts Generally implemented as individual hardware vectors with a small amount of program memory at the location l ISR is what you get – no OS, no threads, no IST l l l Also very common to use interrupts to simulate threads l l l Can use a flag with main loop to get IST behavior for less time critical code Interrupt itself take the place of the Wait. For_XXX or signal Follows very naturally for hardware tasks and timers Generally an “interrupt” statement provided
Interrupt Example static unsigned char g_Timer. Triggered; void main() { Configure. Timer 0(); g_Timer. Triggered = 0; Global. Enable. Interrupt(); while(1) { if(g_Timer. Triggered) { g_Timer. Triggered = 0; //Could also disable the timer interrupt here Do. Timer. Task(); //to avoid a race condition resetting g_Timer. Triggered } //Can put optional sleep here, interrupts can wake up processor } } void Timer 0 ISR(void) interrupt 1 using 2 { g_Timer. Triggered = 1; //Can put other small, quick work here } //Interrupt source 1, attached to vector 2
Switch Statement Implementation l Switch statements can be implemented in various ways l l Specific implementation can also vary based case clauses l l Sequential compares In line table look up for case block Special function with look up table Clean sequence (1, 2, 3, 4, 5) Gaps in sequence (1, 10, 30, 255) Ordering of sequence (5, 4, 1, 2, 3) Knowing which method gets implemented critical to optimizing!
Switch Statement Example switch(c. A) { case 0: c. X = 4; break; case 1: c. X = 10; break; case 2: c. X = 30; break; default: c. X = 0; break; } 0006 0009 000 A 000 B 000 C 000 F 0011 0012 0014 0015 0017 0018 001 A 001 C 001 F 0021 0022 900000 E 0 FF EF 120000 00 0000 01 0000 02 0000 900000 7404 F 0 8015 MOVX MOV LCALL DW DB DW DW ? C 0002: MOV MOVX SJMP DPTR, #c. A A, @DPTR R 7, A A, R 7 ? C? CCASE ? C 0003 00 H ? C 0002 01 H ? C 0004 02 H 00 H ? C 0005 DPTR, #c. X A, #04 H @DPTR, A ? C 0006 . . . More blocks follow for each case
Bit Variables l Some processors have special memory areas and op-codes for single bit storage l Saves overhead of masking operations l Some key from bit fields notation, some need keyword (frequently ‘bit’) l struct { unsigned int foo : 1; } flags; l unsigned int my_bit : 1; l bit my_bit;
Math Tricks l Floating point math VERY expensive on microcontrollers l l No hardware support Typically 32 bits for float, 64 bits for double Support provided by a BIG library Can use fixed point math in many cases l l Basically the same as integer math, however move the decimal inside the integer. Binary number is really: l l To make a fixed point number just adjust the exponents: l l l 2^7 + 2^6 +… 2^2 + 2^1 + 2^0 2^6 + 2^5 + … 2^1 + 2^0 + 2^-1 : Note 2^-1 = 0. 5 Assume 8 bit value: Range = [0, 255] Assume one binary decimal point l l l XXXXXX. X Range is now [0, 127. 5] All the internal math stays the same so long as only fixed point numbers with the same binary point location used together!
More Math Tricks You may not have multiply and/or divide ops! l Decomposing operations can help l X*5=X*4+X (X * 4) can become 2 shift left operations l Formulas should also be restructured for math available: Y=ax^2 + bx + c : 1 Pow or Mult, 2 Add Y = x (ax + b) + c : 2 Mult, 2 Add l Lookup tables can be great for limited domain problems
Optimization Step 0 – Before coding anything think about risk points and prototype unknowns!!! l Step 1 – Get it working!! l l Fast but wrong is of no use to anyone Optimization will typically reduce readability Step 2 – Profile to know where to optimize l l Usually one or two routines are critical You need to have specific performance metrics to target
Optimization l Step 3 – Let the tools do as much as they can Turn off debugging! l Select the correct memory model l Select the correct optimization level l l Step 4 – Do it manually Read the generated code! Might be able to make a simple code or structure change. l Last – think about assembly coding l
Summary l Microcontroller hardware is much simpler than most of us are used to l Be familiar with the hardware in your microcontroller l Be familiar with your compiler options and how it translates your code l For time or space critical code look at the assembly listing from time to time
Questions?
- Slides: 24