使用串行通信C++发送和接收浮点数 [英] to transmit and receive floating point using serial communication c++

查看:73
本文介绍了使用串行通信C++发送和接收浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 WiringPi 库在 Raspberrypi 上进行串行通信函数 serialPutchar(int fd, unsigned char c) 和 serialGetchar (int fd) 可以很好地发送和接收整数值但不显示浮点

using WiringPi library for serial communication on Raspberrypi the function serialPutchar(int fd, unsigned char c) and serialGetchar (int fd) works fine to send and receive integer value but does not show floating points

发送方

int main ()
{
int fd ;
int count ;
float val;

if ((fd = serialOpen ("/dev/ttyAMA0", 9600)) < 0)
{
fprintf (stderr, "Unable to open serial device: %s\n", strerror 
(errno)) ;
return 1 ;
}

if (wiringPiSetup () == -1)
{
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror 
(errno)) ;
return 1 ;
}
for (count = 0 ; count < 256 ; ){
val=4.1;
fflush (stdout) ;
serialPutchar(fd,val);
++count ;
delay (500) ;
}
printf ("\n");
return 0;}

接收端

 int main ()
 {
 int fd ;

 if ((fd = serialOpen ("/dev/ttyUSB0", 9600)) < 0)
 {
fprintf (stderr, "Unable to open serial device: %s\n", strerror 
(errno)) ;
return 1 ;
}
if (wiringPiSetup () == -1)
{
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror 
(errno)) ;
return 1 ;
}
while(true)

{

  printf ("%f", serialGetchar (fd)) ;
  fflush (stdout) ;
  printf ("\n") ;
}

return 0 ;
}

我预计输出为 4.100000,但实际输出为 0.000000

i expected the output to be 4.100000 but the actual output is 0.000000

对发送和接收浮点数的任何帮助将不胜感激提前致谢

Any help to send and receive floating point numbers will be appreciated Thanks in advance

推荐答案

您需要做的是将浮点数分解为字节,然后一一发送/接收它们.注意:以下代码假设发送方和接收方使用相同的字节序系统.

What you need to do is break the float into bytes and then send/receive them one by one. Note: The following code assumes sender and receiver using same endian system.

//Sender
float f = 4.1;
int i = 0;
for (; i < sizeof(float); ++i)
    serialPutchar(fd, ((char*)& f)[i]);


// receiver
float f;
int i = 0;
for (; i < sizeof(float); ++i)
    ((char*)& f)[i]) = serialGetchar(fd);

这篇关于使用串行通信C++发送和接收浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆