LPCopen coding style and library design

Discussion created by lpcware Employee on Jun 15, 2016
Latest reply on Jun 15, 2016 by lpcware
Content originally posted in LPCWare by Strahlex on Fri Jan 24 02:45:47 MST 2014
Hello NXP developers,

I am working since approximately one and a half year with the NXP Cortex M3 MCUs and would like to share my opinion about LPCopen (and previous NXP libraries). Please do not take my advice personal, but consider it as information to make your libraries better and, therefore, creating better user experience for you customers. So will discuss a few things in general about the library design and with the ring buffer implementation as example. So let's start:
1. Create a uniform implementation for all LPC1xxx series. The fact that you have to provide different packages for different series and even MCUs actually means that your cross-series design is not good. I solved that in my library implementation by using a special driver level below the implementation level of the peripherals.
2. Use Git or any other version management system. It would make it easier for the community to collaborate.
3. Use ANSI C and ISO-C99 datatypes everywhere and never use int one embedded platforms. Here are some reasons why: http://embeddedgurus.com/stack-overflow/2009/07/efficient-c-tips-10-use-unsigned-integers/
4. Never use pointer arithmetic on embedded systems. It is hard to verify whether a pointer is correct or not and, furthermore, pointer arithmetic can give you unexpected results. In case of the ring buffer implementation I would recommend to switch to array indexing. It gave me absolute deterministic results compared to pointer arithmetic which can do unexspected things when memory is rare.
5. Use data type specific number formatting like for example 0u, 0xFFu, 0b1010, 1.2 and so on. It makes he code more readable (you can easily identify signed values) and makes shure the compiler knows which data type was meant.
6. Use enums to describe peripheral settings this makes the code more readable.
7. Make use of the fast data types defined in stdint.h (e.g. uint_fast16_t).
8. Avoid using one line ifs and loops always use braces to avoid issues.
9. Use a linter (MISRA C will show you most of the above issues).
10. Create module tests e.g. using CUnit.
11. Do code reviews a few months after the development (when you have forgotten how you implemented everything) to make sure your library design is sane and any developers coming after you will understand the code as well.

In general I would recommend reading this blog carefully, it describes a lot of flaws possible in embedded C development: http://embeddedgurus.com/stack-overflow/category/efficient-cc/