Thursday, 25 October 2012

Embedded C, Defining Common Types

How do you write portable C code that you can use on any processor architecture or compiler and even unit test such code on a Windows PC? This is one problem I've been addressing over the last year or so as I've written firmware for several processor architectures PICS, Renesas H8's and Infineon 166.

The first problem is that an int can be 1,2 or 4 bytes in size and it depends on the compiler, processor and OS. In this post I'll show how to use precisely defined types that you can use throughout your code so that you will not need to worry about the size of types.

Common types that you will use are signed and unsigned ints, so these will need to be defined and standardized:

The C language is missing the bool type, so I define this as well, which is great as I can now mix the embedded C code with the C++ unit test harness code running on my Windows PC. I also prefer returning a bool instead of error codes so as to keep things simple.

Here is an example of my defines.h that I use when writing C projects for PIC micro-controllers.

About Me

Pig Dog Bay was born in an inn deep in the Staffordshire moorlands. He lived in a small box under the pool table and was fed on pork scratchings left in the ash trays.

One day a raucous rock band called Motorhead played at the inn causing mayhem, so Pig Dog spied his chance and had it away on his trotters.

The nights were cold and after many days of trotting, a weary Pig Dog took shelter in a green house where big ripe tomatoes grew. The next day the owners son spotted Pig Dog and took pity on the hungry creature. Together they played computer games on a dusty old ZX Spectrum, eventually the son left and Pig Dog was all alone. Dabbing at the rubber keys, Pig Dog had made a computer program:

PIG DOG BAY

PIG DOG BAY

PIG DOG BAY

Whizzed up the screen. This pleased Pig Dog greatly. Many years later the son returned and was so happy to see his old friend, he gave Pig Dog his Google Nexus 7. Pig Dog squealed with glee and now wanted to show the world his little apps.