请大牛们帮忙看一下,我的linux串口程序只能单端传输数据
现在正在写一个关于linux下串口通信的程序,在网上看了很多范例程序,参照他们写了一个自己的测试程序,但是只能实现从一端到另一端的数据传输,反过来传输时,可以写数据成功但是在读取数据时就会阻塞不能接收到数据。代码如下请忙满看一下是哪里的问题,谢谢了。
接受端的程序:
int fd = 0;
struct termios Opt;
int res;
int nread;
char buff[512] = {0};
int nums = 0;
bzero(&Opt,sizeof(Opt));
fd = open( "/dev/ttyS0", O_RDWR );
if (fd <= 0)
{
perror("open ttyS0 failed!\n");
exit(-1);
}
tcgetattr(fd, &Opt);
tcflush(fd,TCIOFLUSH);
cfsetispeed(&Opt,B9600);
cfsetospeed(&Opt,B9600);
res = tcsetattr(fd,TCSANOW,&Opt);
if (res != 0)
{
perror("tcsetattr fd !\n");
return -1;
}
tcflush(fd,TCIOFLUSH);
bzero(&Opt,sizeof(Opt));
tcgetattr(fd,&Opt);
Opt.c_cflag &= ~CSIZE;
Opt.c_cflag |= CS8;
Opt.c_cflag &= ~PARENB;
Opt.c_iflag &= ~INPCK;
Opt.c_cflag &= ~CSTOPB;
// Opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// Opt.c_oflag &= ~OPOST;
tcflush(fd,TCIOFLUSH);
Opt.c_cc[VTIME] = 150;
Opt.c_cc[VMIN] = 0;
res = tcsetattr(fd,TCSANOW,&Opt);
if (res != 0)
{
perror("tcsetattr fd !\n");
return -1;
}
tcflush(fd,TCIOFLUSH);
while(1)
{
if ((nread = read(fd,buff,512)) > 0)
{
if (nread == 12)
if ((nums++) == 100)
break;
buff[nread] = '\0';
printf("the length is %d, %s \n",nread,buff);
}
}
发送端的程序为:
int fd = 0;
struct termios Opt;
int res;
int nread;
char buff[512] = {0};
int nums = 0;
bzero(&Opt,sizeof(Opt));
fd = open( "/dev/ttyS0", O_RDWR );
if (fd <= 0)
{
perror("open ttyS0 failed!\n");
exit(-1);
}
tcgetattr(fd, &Opt);
tcflush(fd,TCIOFLUSH);
cfsetispeed(&Opt,B9600);
cfsetospeed(&Opt,B9600);
res = tcsetattr(fd,TCSANOW,&Opt);
if (res != 0)
{
perror("tcsetattr fd !\n");
return -1;
}
tcflush(fd,TCIOFLUSH);
bzero(&Opt,sizeof(Opt));
tcgetattr(fd,&Opt);
Opt.c_cflag &= ~CSIZE;
Opt.c_cflag |= CS8;
Opt.c_cflag &= ~PARENB;
Opt.c_iflag &= ~INPCK;
Opt.c_cflag &= ~CSTOPB;
Opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
Opt.c_oflag &= ~OPOST;
tcflush(fd,TCIOFLUSH);
Opt.c_cc[VTIME] = 150;
Opt.c_cc[VMIN] = 0;
res = tcsetattr(fd,TCSANOW,&Opt);
if (res != 0)
{
perror("tcsetattr fd !\n");
return -1;
}
tcflush(fd,TCIOFLUSH);
strcpy(buff,"hello world!");
while (1)
{
if ((nread = write(fd,buff,strlen(buff))) > 0)
{
if (nread == 12)
if ((nums++) == 100)
break;
printf("the write length is %d, %s \n",nread,buff);
}
}
请帮忙看一下是哪里的问题,谢谢了。