我在Linux平台上编写了一个代码,用于读取串口数据,我的代码如下:
int fd;
char *rbuff=NULL;
struct termios new_opt, old_opt;
int ret;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
if( fd == -1 )
{
printf("Can't open file: %s\n", strerror(errno));
return -1;
}
tcgetattr(fd, &old_opt);
new_opt.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
new_opt.c_iflag = IGNPAR /*| ICRNL*/;
new_opt.c_oflag = 0;
new_opt.c_lflag = ICANON;
tcsetattr(fd, TCSANOW, &new_opt);
rbuff = malloc(NBUFF);
printf("reading..\n");
memset(rbuff,0x00,NBUFF);
ret = read(fd, rbuff, NBUFF);
printf("value:%s",rbuff);
if(ret == -1)
{
printf("Read error:%s\n",strerror(errno));
return -1;
}
tcsetattr(fd, TCSANOW, &old_opt);
close(fd);
Run Code Online (Sandbox Code Playgroud)
我的问题是上面的代码没有读取传输的第一个数据,然后第二个传输数据是垃圾,然后第三个是正常数据.
我错过了串口设置吗?
谢谢.
如果您谈论的是硬件串行端口 (RS-232),我建议使用 BusBee 等串行端口分析器来查看实际发送到串行端口的内容。如果您使用总线蜂,请记住在 BusBee 之前放置一个收发器,以将电压电平从 RS-232 调整为 TTL。或者,如果您可以使用示波器,则可以使用它来读取 RS-232 线路上的信号并自行解码字节。