红联Linux门户
Linux帮助

linux下的串口通信问题

发布时间:2009-04-08 22:37:34来源:红联作者:zhongbin
[i=s] 本帖最后由 zhongbin 于 2009-4-8 23:18 编辑 [/i]

#include
#include
#include
#include
#include
#include
#include
#include
#include "xiaolian.h"

#define datalen 13

int main()
{
unsigned char wdata[datalen]="PA00SA0202NT";
unsigned char rdata[datalen];
struct timeval tv;
int fd;
int i;
int j;
int n;
int rc;
struct termios options;
printf(" %s \n",wdata);
/*open*/
fd=open("/dev/ttyS0",O_RDWR | O_NOCTTY | O_NDELAY);
if(fd==-1)
{
printf("%s open false\n","/dev/ttyS0");
exit(0);
}
fcntl(fd, F_SETFL, 0);
tcgetattr(fd, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);

options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;

options.c_iflag &= ~(INPCK | ISTRIP | BRKINT | IXON |IXANY |IXOFF);
options.c_cc[VMIN] = 50;
options.c_cc[VTIME] = 30;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &options);

/*write*/
if(datalen!=write(fd,wdata,datalen))
printf("write data error!\n");
else
printf("write data OK!\n");

fd_set readfd;
FD_ZERO(&readfd);
FD_SET(fd,&readfd);
tv.tv_sec = 0;
tv.tv_usec = 10000;
rc=select(fd+1,NULL,&readfd,NULL,&tv);
printf(" rc=%d \n",rc);

if(rc>0)
{ j=0;
while(datalen)
{

printf("while!\n");
n=read(fd,&rdata[j], 1);
printf("n=%d \n",n);
if(n>0)
{

printf("Read %d bytes.\nRead data: ",n);
printf("%d ", rdata[j]);
j++;

}
else
{
printf("Read data failed!\n");
break;
}
datalen--;
}

}

close(fd);
}

为什么我的程序在运行时,程序停在read()这里, printf("n=%d \n",n);没有执行?求助!
文章评论

共有 0 条评论