问题
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
回答1:
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);
回答2:
A float
needs to send data as multiple bytes, not just one call of serialPutchar()
which sends only 1.
When receiving multiple bytes over a serial channel, it is easy for a byte to be dropped or for the receiver to begin in mid-stream. I recommend employing framing the data, in some fashion to cope.
Example: Send as text with sentinels
// Sender
char buf[30];
snprintf(buf, sizeof buf, "<%a>", some_float);
serialPutString(fd, buf);
// Receive
while (serialGerChar(fd) != '<') {
;
}
char buf[30*2];
for (i=0; i<sizeof buf - 1; i++) {
buf[i] = serialGetChar(fd);
if (buf[i] == '>') {
break;
}
}
buf[i] = '\0';
f = strtod(buf, &endptr);
// additional checks possible here.
Robust code does not assume incoming data is well formed and check for various problem like incomplete, excessive, non-numeric text.
来源:https://stackoverflow.com/questions/57308789/to-transmit-and-receive-floating-point-using-serial-communication-c