Saturday, August 15, 2009

Embedded systems Coding: Issues and techniques - Part 1

In Embedded systems, you may wonder that though you have done logically correct coding, it is not working practically on board as you expect. Could you imagine what are all things may cause such problems in embedded systems? Are you aware of coding issues related with compiler optimization, I/O synchronization, Cache write-back, edge triggered interrupts, etc.,? Let me guide you how-to code with some of these issues.

Optimization is an unavoidable one to improve the speed and to reduce the size of the code in embedded systems. But, the compiler will have strict eyes on your code and generate more tricky code which may result in unexpected result. Look at the following typical case:

What do you intend to do in the above code? It is a polling where each time it should read the status register and check for the status update by the hardware. But the compiler will think in more smarter way that why to read the SAME memory location each time unnecessarily since the content is going to be the SAME. The compiler will not know that its content is going to be changed by hardware after sometime. So, it is dare enough to generate the assembly code which is equivalent to

which may result in infinite loop in case the IO_COMPLETED flag is not set when the code reads the status register for the first time.
So, what do you have to do? You have to understand that IO mapped memory is different from the real memory and its content is subjected to change internally by hardware without any external CPU write. So, you have to teach the compiler to treat them separately.

Declare the IO memory locations as volatile so that the compiler will not optimize the read/write operations of such volatile memory locations. So, the above code will work perfect with optimization.

No comments: