【发布时间】:2014-03-20 08:34:35
【问题描述】:
我正在使用串行端口从设备接收数据。通信正常,但读取数据时出现问题。我正在使用 Linux (Ubuntu)。
这是我的代码:
int OpenPort(char *PortName, int *FileDesc) {
*FileDesc = open (PortName, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
perror("fakap");
return (P_OPEN_ERROR);
}
else return(P_OPEN_SUCCESS);
};
int SetPortAtributes (int fd, int speed, int parity) {
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
perror("error %d from tcgetattr");
return -1;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag |= (IGNBRK | IGNPAR);,
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_iflag &= ~(ISTRIP);
tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD | HUPCL); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
tty.c_lflag = 0;
if (tcsetattr (fd, TCSANOW, &tty) != 0)
{
perror("error %d from tcsetattr");
return -1;
}
return 0;
}
阅读部分:
void PortRead(int *FileDesc) {
memset(&recBuff[0], 0, sizeof(recBuff)); //clear buff
int n = read (*FileDesc, recBuff, sizeof(recBuff)); // read
printf("n: %d \n", n);
int i = 0;
for(i = 0;i<n;i++) {
recData.buf[i].b_int = recBuff[i]; // put rec buff to ANS_u type variable
}
};
在我收到大于 8 个字节的消息之前一切正常。 read() 读取的字节数不超过 8 个,因此我必须第二次使用 read() 来读取所有数据。 当我使用 GtkTerm 时一切正常,但是在 C 实现过程中出现了问题。
【问题讨论】:
-
呃,我们不知道
recBuff是什么... -
其定义为 char recBuff[40]
-
您没有检查读取返回值。如果 EINTR 发生,您将得到 n=-1 并且您的代码会忽略它(因此您重试第二次读取)。尝试检查 n==-1 并报告结果
-
我可以用 printf() 检查 n 值,没有发生错误。
标签: c linux serial-port tty