在嵌入式C中使用带有sprintf()的浮点数

adi*_*tya 26 c embedded floating-point printf

大家好,我想知道float变量是否可以在sprintf()函数中使用.

就像,如果我们写:

sprintf(str,"adc_read = %d \n",adc_read);
Run Code Online (Sandbox Code Playgroud)

where adc_read是整数变量,它将存储字符串

"adc_read = 1023 \n"

str(假设 adc_read = 1023)

如何使用float变量代替整数?

pax*_*blo 47

由于您使用的是嵌入式平台,因此您很可能无法使用printf()-style函数的全部功能.

假设你有浮动(仍然不一定是嵌入式东西的给定),你可以使用类似的东西来模拟它:

char str[100];
float adc_read = 678.0123;

char *tmpSign = (adc_read < 0) ? "-" : "";
float tmpVal = (adc_read < 0) ? -adc_read : adc_read;

int tmpInt1 = tmpVal;                  // Get the integer (678).
float tmpFrac = tmpVal - tmpInt1;      // Get fraction (0.0123).
int tmpInt2 = trunc(tmpFrac * 10000);  // Turn into integer (123).

// Print as parts, note that you need 0-padding for fractional bit.

sprintf (str, "adc_read = %s%d.%04d\n", tmpSign, tmpInt1, tmpInt2);
Run Code Online (Sandbox Code Playgroud)

您需要根据整数的大小限制小数点后的字符数.例如,对于16位有符号整数,您将被限制为四位数(9,999是可以表示的最大十次幂的幂).

但是,有一些方法可以通过进一步处理小数部分来处理这个问题,每次将它移动四位十进制数(并使用/减去整数部分),直到获得所需的精度.


更新:

最后一点,您提到您正在使用avr-gcc其他答案之一.我发现以下网页似乎描述了您需要%f此处printf()语句中使用的内容.

正如我最初所怀疑的那样,你需要做一些额外的工作来获得浮点支持.这是因为嵌入式东西很少需要浮点(至少没有我曾经做过的东西).它涉及在makefile中设置额外的参数并与额外的库链接.

但是,由于需要处理通用输出格式,这可能会大大增加您的代码大小.如果你可以将浮点输出限制在4位小数或更少,我建议将我的代码转换为函数并使用它 - 它可能会占用更少的空间.

如果链接消失,你需要做的是确保你的gcc命令有"-Wl,-u,vfprintf -lprintf_flt -lm".这转换为:

  • 强制vfprintf最初是未定义的(以便链接器必须解析它).
  • 指定printf()用于搜索的浮点库.
  • 指定要搜索的数学库.

  • 对于 gcc / stm32,添加这个对我有用:LDFLAGS += -u _printf_float (2认同)

小智 6

这样的事情是不是真的更容易:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char str[10];
float adc_read = 678.0123;

dtostrf( adc_read, 3, 4, temp );
sprintf(str,"adc_read = %10s \n", temp);
printf(temp);
Run Code Online (Sandbox Code Playgroud)