gcc中如何使用串口输出float double型数据

avr gcc中的printf函数不支持%f输出

注意在gcc中float double型数据一律处理为单精度(4 bytes)

有两种做法:
1、将浮点数分解为4个字节,分别送出,接收端再这4个字节合并转化为将浮点数

示例如下:
#include <stdio.h> 

typedef union 
{  
   float  f;  
   unsigned char u[4];  
}Float4Byte;  

int main(void) 

   Float4Byte m1,m2; 
   m1.f=-1.2356; 
   m2.u[0]=m1.u[0];      //假设这里经过了一个传输过程. 
   m2.u[1]=m1.u[1]; 
   m2.u[2]=m1.u[2]; 
   m2.u[3]=m1.u[3]; 

   printf("m1=%f
",m1.f); 
   printf("m2=%f
",m2.f); 
   return 0; 


运行结果: 
m1=-1.235600 
m2=-1.235600 


2、将浮点数转化字符串,逐个字符发送出去,接收端再将这些字符组合成字符串,如需运算再将字符串转化为浮点数。

如使用 sprint函数进行字符串拼接

3、将浮点数放大*10、*100、*1000等,转化成整型数

4、使用AVR GCC提供的sprintf和浮点支持

使用sprintf很方便,include <stdio.h> 即可. 但是要是想格式化浮点数,则需要下面的步骤,简单描述就是:
1. 需要和libprintf_flt.a  libm.a 链接
2. 需要传递link option:-Wl,-u,vfprint

这个将使用2-3k的code空间. 想想,还是字符拼接比较经

http://hi.baidu.com/systemsoftware/blog/item/c7228b7fd6c6ea1f29388a92.html

参考:
http://winavr.scienceprog.com/avr-gcc-tutorial/using-sprintf--function-for-float-numbers-in-avr-gcc.html

猜你喜欢

转载自blog.csdn.net/catshit322/article/details/6672387
今日推荐