How to read the serial port buffer completely

Hi, I am writing a program sending commands to a GPS and read the data from it. I use serial port to communicate with the GPS.

Here are parts of the code:

//Open the ser port
fd_ser = open( “/dev/ser1”, O_RDWR);

//Check configuration of GPS
tcflush(fd_ser, TCIOFLUSH);

write(fd_ser, “log comconfiga once\r”, sizeof(“log comconfiga once\r”));


int temp = 0;
read(fd_ser, cbuffer, sizeof(cbuffer));
printf(“Config test 1 : %s\n”, cbuffer);
}while(!strstr(cbuffer, “COMCONFIGA”));

printf(“Config test 2 : %d\n%s\n”, temp, cbuffer);
if(strstr(cbuffer, “COMCONFIGA”))
printf("\n\nConfig of GPS is OK. \n\n");
printf("\n\nConfig of GPS failed. \n\n");

The data comes from the GPS should be as long as about ‘char cbuffer[500]’. Unless I use sleep(1), the data in cbuffer will be incomplete. The print results of the do…while are:
(Suppose the GPS data should be: #abcdefghijklmnopq…)
Config test 1 : #a //incomplete
Config test 1 : bcd //incomplete
Config test 1 : efghijklmnopq… //complete

Any suggestion?

This works but it’s bad practice instead:

const char * msg = “log comconfiga once\r”;

// — the -1 is important otherwise you’ll be sending a 0 ( string terminator )
if ( write ( fd_ser, msg, sizeof( msg ) -1 ) != sizeof( msg ) -1 )
// handle error in transmission

There are many ways to do this. The best is to read until a timeout occurs ( treat it has an error ), or read util the /r or /n is received which should indicated a end of command.

You can do a while loop reading 1 byte at a time, you can use readconf() to read up to x amount of data and wait up until x ms. You could set the port in non blocking mode and read as much data as possible until you get the /r/n. There are fancier method but I thing you should start from there

Thanks for your suggestion, mario. Now I am using readcond but I think I’ll try to set the port in non blocking mode though I am not sure whether there will be /r/n or not at the end of the data from GPS.

Yes there will! Been there, done that :wink:



One more question. What about the VFWD character in the c_cc member of the termios structure? Can I set it to be \r or \n?