Search code examples
c++clinuxserial-portbuffer

buffer problem when making serial communication with C++


I am working on for serial communication using C++. I am calling linux command with C++. One port I am using works as transmitter and the other part is working as a receiver.

This is how transmitter works,

#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <fstream>

using namespace std;

ofstream wfile;
char byte[40];
int n=0;

int main()
{
  while(true)
    {
      wfile.open("/dev/ttyUSB1");
      sprintf(byte,"message : %d\n",n);
      wfile << byte;
      wfile.close();
      printf("%s",byte);
      n++;
      sleep(1);
    }
}

And in the terminal window, I see result as

message : 0
message : 1
message : 2
message : 3
message : 4
message : 5
message : 6
message : 7
message : 8
message : 9

In the receiver part, my C++ script is written as

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char var[100];
  FILE *fp;
  while(true)
    {
      fp=popen("cat /dev/ttyUSB0","r");
      fgets(var,sizeof(var),fp);
      printf("%s",var);
      pclose(fp);
    }
  return 0;
}

I am expecting to get same result at the terminal window of my receiver's side.

I see a result something like

message : 1
 1
 1
 1
 1
 1
 1
 1
 1
... (repeats about 100 time)

 1
 1
 1
message : 2







...(void for about 100 line)



message : 3






...


message : 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
: 4
...

Something like this. I am assuming this is a problem with the buffer in the serial port. Moreover, Receiver is showing messages from old buffers which is not even initialized! Is there any way to fix this as I intended?


Solution

  • Things to fix

    Check return value of fgets()

    Simplify as desired.

    if (fgets(var,sizeof(var),fp)) {
      printf("<%s>\n",var);
    } else {
      printf("Nothing this time.\n");
    }
    

    GTG