Embedded Programming Tips
By no means is this guide meant to be an exhaustive list of all considerations when programming on an embedded system. However, these are some of the most important rules and conditions to keep in mind when writing low-level code running "on the metal", along with what may be found in Code Style and Debugging:
Hardware:
Read the datasheet. The datasheet is always right. Check the corner cases. Check the header files. Errors can be hiding anywhere.
Check the hardware:
Is there power where it belongs? Is it the right voltage?
Are jumpers and connections configured correctly?
Are external devices plugged in as intended?
Is the system alive? Try adding code that continuously responds to stimuli to debug potential lock-ups and resets.
Execution path:
Can the program leave the main function? Doing so will probably execute unintended code.
Do all enabled interrupts have a valid (even if blank) interrupt service routine?
Is the watchdog and reset control (only available on some processors) configured as desired?
Interrupts:
Can interrupts occur here? Should they be able to?
Is this section timing-critical? Should interrupts be temporarily disabled?
Bit-shifts and bit-masks:
Can a multiply or divide instruction be replaced with a bit shift?
Does each bit mask have the correct polarity?
Is the order of operations (| and & evaluate after == for example) respected?
Do bit shifts properly account for a signed or unsigned variable?
Memory usage:
Can this variable be declared with a type using fewer bits (possibly using unsigned types)?
Are dynamic memory allocation calls checked for memory exhaustion?
Will the stack overflow into global variables or the heap?
Are there warnings about sections overlapping after the link? This is almost certainly a sign that a program is too big.
Performance:
Will overflow cause a problem with narrow variables?
Will the use of variables larger than the native variable size cause expensive extended-precision arithmetic?
Are large items passed by value (which may clandestinely copy them)?
Could a hardware peripheral perform the task of this software routine?
Contributing Teams to this Article:
BLRS (Purdue SIGBots)
Last updated