It looks like the issue may be with the VTIME and VMIN settings in the termios structure.
VTIME is the amount of time to wait for data to be received in tenths of a second. In this code, VTIME is set to 1, which means that the read function will wait for 0.1 seconds for data to arrive before returning.
VMIN is the minimum number of characters to read before the read function returns. In this code, VMIN is set to 0, which means that the read function can return as soon as a single character is received.
The behavior you’re seeing could be due to the combination of these settings. Since VMIN is set to 0, the read function can return as soon as a single character is received, but since VTIME is set to 1, it will wait an additional 0.1 seconds before returning. This could explain the delay you’re seeing.
To fix this issue, you could try setting VTIME to 0, which would cause the read function to return immediately when data is received. You could also set VMIN to the number of bytes you expect to receive in a single packet (in this case, 20), which would ensure that the read function doesn’t return until a full packet has been received.
int fd = open(“/dev/ttyLP2”, O_RDWR | O_NOCTTY);
struct termios newtio;
newtio.c_cflag |= B115200;
newtio.c_cflag &= ~PARENB;
newtio.c_iflag &= ~(IXON | IXOFF | IXANY);
newtio.c_cflag &= ~CSTOPB;
newtio.c_cflag |= CS8;
newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
newtio.c_cc[VTIME] = 0; // set VTIME to 0
newtio.c_cc[VMIN] = 20; // set VMIN to 20
newtio.c_oflag &= ~OPOST;
newtio.c_cflag |= (CLOCAL | CREAD);
newtio.c_oflag = 0;
newtio.c_oflag &= ~OPOST;
tcflush(fd,TCIFLUSH);
tcsetattr(fd,TCSANOW,&(newtio));
while(1) {
fd_set read_fds;
FD_ZERO(&(read_fds));
FD_SET(fd,&(read_fds));
timeval tout;
tout.tv_sec = 1;
tout.tv_usec = 0;
rx = 0;
char buffer[20];
while(received < 20) {
int result = select(fd+ 1, &(read_fds), nullptr, nullptr, &(tout));
if (result > 0) {
int tmp = read(fd,(buffer+rx),20-rx);
if(tmp != -1) {
rx += tmp;
}
}
}
/* Data Processing */
}