Since you're on an embedded platform, it's quite possible that you don't have the full range of capabilities from the printf()
-style functions.
Assuming you have floats at all (still not necessarily a given for embedded stuff), you can emulate it with something like:
char str[100];
float adc_read = 678.0123;
int d1 = adc_read; // Get the integer part (678).
float f2 = adc_read - d1; // Get fractional part (678.0123 - 678 = 0.0123).
int d2 = trunc(f2 * 10000); // Turn into integer (123).
//int d2 = (int)(f2 * 10000); // Or this one: Turn into integer.
// Print as parts, note that you need 0-padding for fractional bit.
// Since d1 is 678 and d2 is 123, you get "678.0123".
sprintf (str, "adc_read = %d.%04d\n", d1, d2);
You'll need to restrict how many characters come after the decimal based on the sizes of your integers. For example, with a 16-bit signed integer, you're limited to four digits (9,999 is the largest power-of-ten-minus-one that can be represented). However, you could use repeated fractional bits to get more precision as follows:
char str[100];
float adc_read = 678.01234567;
int d1 = adc_read; // Get the integer part (678).
float f2 = adc_read - d1; // Get fractional part (0.01234567).
int d2 = trunc(f2 * 10000); // Turn into integer (123).
float f3 = f2 * 10000 - d2; // Get next fractional part (0.4567).
int d3 = trunc(f3 * 10000); // Turn into integer (4567).
sprintf (str, "adc_read = %d.%04d%04d\n", d1, d2, d3);
This should work up to the precision of your floats (and you may want to make it a library function so it doesn't look so ugly within the main flow of code).
Check the docs for your embedded platform. Either floats aren't supported by printf()
(likely) or you have to link in some special code.
Update:
One final point, aditya, you mentioned that you were using avr-gcc
in a response to one of the other answers. I found the following web page that seems to describe what you need to do to use %f
in your printf()
statements here.
As I originally suspected, you need to do some extra legwork to get floating point support. This is because embedded stuff rarely needs floating point (at least none of the stuff I've ever done). It involves setting extra parameters in your makefile and linking with extra libraries.
However, that's likely to increase your code size quite a bit due to the need to handle general output formats. If you can restrict your float outputs to 4 decimal places or less, I'd suggest turning my code into a function and just using that - it's likely to take up far less room.
In case that link ever disappears, what you have to do is ensure that your gcc command has "-Wl,-u,vfprintf -lprintf_flt -lm
". This translates to:
- force vfprintf to be initially undefined (so that the linker has to resolve it).
- specify the floating point
printf()
library for searching.
- specify the math library for searching.