我需要学习如何读写串口。出于测试目的,我将传输线连接到接收线并通过示波器检查信号行为。我可以看到写入正常:1个数据字节从Tx传输到Rx。但是函数read(fd, &rcv_val, 1)
返回-1。
使用了不同的端口:" / dev / ttyUSB0"," / dev / ttyS5"。
我在这个网站上看到了类似的问题,但它并没有帮助我解决问题。
代码:
int res = 0;
int fd; /* File descriptor for the port */
int snd_val, rcv_val;
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1){//Could not open the port.
fprintf(stderr, "open_port: Unable to open /dev/ttyUSB0 - %s\n", strerror(errno));
return fd;
}
speed_t baud = B38400;
struct termios settings;
tcgetattr(fd, &settings);
cfsetispeed(&settings, baud); // baud rate
cfsetospeed(&settings, baud); // baud rate
settings.c_cflag &= ~PARENB; // no parity
settings.c_cflag &= ~CSTOPB; // 1 stop bit
settings.c_cflag &= ~CSIZE;
settings.c_cc[VMIN] = 1;
settings.c_cc[VTIME] = 0;
settings.c_cflag |= (CS8 | CLOCAL | CREAD);
tcflush(fd, TCOFLUSH | TCIFLUSH);
tcsetattr(fd, TCSANOW, &settings);// apply the settings
snd_val = 0xA5;
write(fd, &snd_val, 1);
if (res < 0){
printf("Err wr\n");
return res;
}
else printf("send ok\n");
res = read(fd, &rcv_val, 1);
if (res < 0){
printf("Err rd\n");
return res;
}else printf("rcv_val = 0x%02X\n", rcv_val);
return res;