delay serial read function when there is no data reception
Hi,
I have an issue in reading serial port.
The read function takes very less execution time when the data is received, which is appr 80 us.
However, when there is no data on the bus the same function takes a long time which is around 220 ms before it returns.
I monitor the execution time on oscilloscope by toggling some IO line of my PC.
Can someone help me out please.
I have not set any timeouts or enabled blocking mode in my port initialization. Please find below the code for initialization and read function .
/********************************************/
int initport(int fd) {
struct termios options,oldtio;
fd = open("/dev/ttyS2", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) {
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
{
fcntl(fd, F_SETFL, 0);
}
// save current port settings
tcgetattr(fd,&oldtio);
//Get the current options for the port...
tcgetattr(fd, &options);
// Set the baud rates to 9600...
long baudRate = B9600; //Please set baud rate as per you settings
cfsetispeed(&options, baudRate);
cfsetospeed(&options, baudRate);
// Enable the receiver and set local mode...
options.c_cflag |= (CLOCAL | CREAD);
//options.c_oflag &= OPOST;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST; // No output processing
options.c_oflag &= ~ONLCR; // Don't convert linefeeds
options.c_lflag = 0; // no local flags
options.c_cflag |= HUPCL; // Drop DTR on close
// Clear line
tcflush(fd,TCIFLUSH);
// Set the new options for the port...
tcsetattr(fd, TCSANOW, &options);
return 1;
}
/**********************************************************/
/**********************************************************/
int readport(int fd, unsigned char *result) {
int iIn = read(fd, result, 64);
result[iIn] = 0x00;
if (iIn < 0) {
if (errno == EAGAIN) {
printf("SERIAL EAGAIN ERROR\n");
printf("SERIAL read error %d %s\n", errno,
strerror(errno));
return 0;
} else {
printf("SERIAL read error %d %s\n", errno,
strerror(errno));
return 0;
}
}
return 1;
}
/**********************************************************/
/**********************************************************/
int serialcomm(unsigned char *result1, char sCmd[]) {
if (!writeport(fd, sCmd)) {
printf("write failed\n");
close(fd);
return 1;
}
usleep(SLPDLY);
fcntl(fd, F_SETFL, FNDELAY); // don't block serial read
if (!readport(fd,result1)) {
printf("read failed\n");
return 1;
}
printf("readport=%s\n", result1);
return 0;
}
|