current-events

printf for embedded systems

I'm publishing a printf library for embedded applications. I know, does the world really need yet another printf? Probably not, but this one is a little different from all the others that I found. For starters, it doesn't even do printf! It has one primary function, snprintf(), which is exactly like the standard library call and generates a string that is bounded so it can't overflow its buffer.

In a memory constrained system there's always the challenge of how big a buffer to allocate to snprintf; large enough to hold the output string but not wastefully large. You can pass NULL as a buffer to the function and it will still return the correct value of the resultant string length. With this knowedge you can then call the function again with a buffer of the precise size needed.

An alternative function allows you to pass a malloc-compatible function pointer that will be called when snprintf has determined the string length. The string will then be copied into the allocated buffer.

The library also supports 64 bit integers. If your system uses large integers for high-precision fixed point operations you can output these values in a decimial, hex, scientific, or engineering notation.

The source code is well documented and straightforward so it can be easily modified. The only non-obvious code is the divide-by-10 that is required for decimal conversion. I wanted to avoid pulling in a divide library for code size and performance reasons. I encourage you to read the code and follow the link to Douglas Jones' excellent treatise on binary to decimal conversion if you are interested.

This library is free and MIT licensed so you can do anything with it. It is on the ee-quipment github at

https://github.com/ee-quipment/printf-embedded

Enjoy!

 


Older Post