我正在测试发送和接收程序,代码如下
main()函数如下:
#include "lib.h"
int fd;
int initport(int fd) {
struct termios options;
// Get the current options for the port...
tcgetattr(fd, &options;);
// Set the baud rates to 19200...
cfsetispeed(&options;, B9600);
cfsetospeed(&options;, B9600);
// Enable the receiver and set local mode...
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
// Set the new options for the port...
tcsetattr(fd, TCSANOW, &options;);
return 1;
}
int main(int argc, char **argv) {
fd = open("/dev/pts/2", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open_port: Unable to open /dev/pts/1 - ");
return 1;
} else {
fcntl(fd, F_SETFL, 0);
}
printf("baud=%d\n", getbaud(fd));
initport(fd);
printf("baud=%d\n", getbaud(fd));
char sCmd[254];
sCmd[0] = 0x41;
sCmd[1] = 0x42;
sCmd[2] = 0x43;
sCmd[3] = 0x00;
if (!writeport(fd, sCmd)) {
printf("write failed\n");
close(fd);
return 1;
}
printf("written:%s\n", sCmd);
usleep(500000);
char sResult[254];
fcntl(fd, F_SETFL, FNDELAY);
if (!readport(fd,sResult)) {
printf("read failed\n");
close(fd);
return 1;
}
printf("readport=%s\n", sResult);
close(fd);
return 0;
}
lib.h 包含读取和写入代码,如下所示:
用C解析和读取数据帧?
并得到了问题:
为了测试串口,我使用了 socat (https://help.ubuntu.com/community/VirtualSerialPort)在 Linux 上创建一对串行端口并使用这些端口测试我的程序。
程序第一次发送数据,程序接收数据就ok了。但是,如果我再次读取甚至重新写入新数据到串口中,返回数据始终为空,直到我停止虚拟串口并再次启动它,然后写入和读取数据都可以,但仍然只是一度。
(在实际情况下,发送部分将由另一个设备完成,我只是负责从串口读取数据。我编写这两个部分只是为了测试我的读取代码。)
有人有什么想法吗?