Efficient coding for small real-time systems.

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:


  1. Global variables, and use of goto are not sackable offences
  2. Use Q-format fractional binary numbers in place of floats/doubles
  3. Do a condition check when posting to a mailbox to prevent overflows
  4. Don't use the register keyword unless you really need it.
  5. Use the volatile keyword when approbriate
  6. Avoid printf and sprintf - these are q uite time consuming
  7. Avoid large arrays initialised to zero (if required, malloc them and initialise manually
    to zero at program start).
  8. Minimise depth of function calls (stack movements/context saves are
    time consuming and wasteful of RAM).
  9. Be careful of variable types/sizes/alignments and use of struct/unions
  10. 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).
  11. Consider hand-coding critical functions in assembler
  12. Limit number of arguments to functions to 3 (to avoid stack usage)
  13. Try not to copy arrays or structures - operate on these in place if possible
  14. Merge loops together
  15. Some processors are more efficient with loops that count down to zero
  16. Try to limit pointer arithmetic to match the CPU you're using
  17. Compile the same stuff on your PC and test it out in a different environment (good also for black-box testing on it)
  18. Do periodic code-walkthroughs (does the structure make sense?), but try not to expand the code just to make it look neat
  19. Use memcopy for copying large structures or arrays - it is usually optimised for the CPU (unlike your attempt using a for loop)
  20. Do NOT write in C++ on a microcontroller!