c++craspberry-pi3serial-communicationwiringpi

to transmit and receive floating point using serial communication c++


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

sender side

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;}

Receiver side

 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 ;
}

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


Solution

  • 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);