Written by Ian on Wednesday 03/01/07
Writing software for microcontrollers in real-time systems is totally different to coding for a desktop PC. It might feel the same, the high-level language might be the same, even the compiler - but the constraints on what you can do are totally different. Here are a list of 20 hints and tips that can help you write efficient (and working) real-time code:
- Global variables, and use of goto are not sackable offences
- Use Q-format fractional binary numbers in place of floats/doubles
- Do a condition check when posting to a mailbox to prevent overflows
- Don't use the register keyword unless you really need it.
- Use the volatile keyword when approbriate
- Avoid printf and sprintf - these are q uite time consuming
- Avoid large arrays initialised to zero (if required, malloc them and initialise manually
to zero at program start).
- Minimise depth of function calls (stack movements/context saves are
time consuming and wasteful of RAM).
- Be careful of variable types/sizes/alignments and use of struct/unions
- Compile code with the -pg flag to gcc to write profile information for the gprof
program to examine (trace of function calls, times called and % of execution time).
- Consider hand-coding critical functions in assembler
- Limit number of arguments to functions to 3 (to avoid stack usage)
- Try not to copy arrays or structures - operate on these in place if possible
- Merge loops together
- Some processors are more efficient with loops that count down to zero
- Try to limit pointer arithmetic to match the CPU you're using
- Compile the same stuff on your PC and test it out in a different environment (good also for black-box testing on it)
- Do periodic code-walkthroughs (does the structure make sense?), but try not to expand the code just to make it look neat
- Use memcopy for copying large structures or arrays - it is usually optimised for the CPU (unlike your attempt using a for loop)
- Do NOT write in C++ on a microcontroller!