C tips for embedded programming

Some very useful resource in writing this post were: an article on  Embedded.com , Nigel Jones’ “C Test” and C coding tips published under cprogramming.com website.

The driving idea was to share my knowledge with other “embedded programmers” but also to debate about several aspects which inherently occur when writing C code for microcontrollers. Those are some general guidelines which I usually try to follow in order to write more efficient code.

It is not very easy to find a starting point in this discussion, but I will “dump” things which I have into my mind along with those found on various web resources. I will struggle to cover embedded-specific topics as interrupts, I/O, timers, variable length, compiler particularities, C standard specifics. Unfortunately not all of them will be deeply explained in this post so I will come back later.

When you writing code for a certain microcontroller/microprocessor type first thing to take into consideration, in my opinion, is that the data type size should be appropriate for CPU used. For an 8-bit processor is more effective to work with 8-bit variables, same for 32-bit CPU and so on.

Another “rule of thumb” in programming (this time also in desktop programming) is that each line of code must have a corresponding line of comment or in any case, there should not be a big discrepancy in between “real code quantity” and its associated number of comment lines.

Be careful of some “delays” that you want to introduce in your embedded C code. Many compilers consider the “empty delay loops” as not useful code, so they are removed causing “unexpected behavior”. For example:


void delay(unsigned int);
//highly time dependent code
sent_data (0xAA);
delay(100);
sent_data (0x55);
delay(100);
void delay(unsigned int time)
{
for (i=0;i<10;i++); //considered to be not useful code
}

delay function can be transformed in

void (unsigned int time)
{
}

It is better and safer to use nop() instructions in case if corresponding microprocessors’ instruction set supports them.

Volatile meaning is…

find out about volatile meaning