当前位置: 技术问答>linux和unix
关于串口程序的问题
来源: 互联网 发布时间:2016-11-15
本文导语: 最近要做个串口通信程序,由linux通过usb转串口向网关设备发送0xffff474d,就能收到网关采集到的数据,在windows和linux的串口调试助手都可以看到能收到数据,可是我自己写的程序确怎么都读不出来,不过我运行...
最近要做个串口通信程序,由linux通过usb转串口向网关设备发送0xffff474d,就能收到网关采集到的数据,在windows和linux的串口调试助手都可以看到能收到数据,可是我自己写的程序确怎么都读不出来,不过我运行自己的程序时确在调试助手里看到能读的数据,请问我读取的部分哪里出了问题呢?以下是我的程序,麻烦高手给分析下,多谢了!
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
main()
{
int fd;
int i,ret;
int readcount;
int n = 0;
FILE* fp = NULL;
struct timeval tv;
fd_set rdfds;
if((fp=fopen("/dev/ttyUSB0","rb+"))==NULL)
{
perror("error");
return -1;
}
setbuf(fp,NULL);
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK); //默认为阻塞读方式
if(fd == -1)
{
perror("open serial n");
exit(0);
}
struct termios opt,old_termios;
tcgetattr(fd,&old_termios);
bzero(&opt,sizeof(opt));
cfsetispeed(&opt, B38400);
cfsetospeed(&opt, B38400);
opt.c_cflag |= (CLOCAL | CREAD);
opt.c_cflag &= ~CSIZE; //屏蔽字符大小位
opt.c_cflag |= CS8; //使用8位数据位
opt.c_cflag &= ~PARENB;
opt.c_cflag &= ~INPCK; //无奇偶校验
opt.c_cflag &= ~CSTOPB; //1位停止位
opt.c_cflag &= ~CRTSCTS;
opt.c_cflag &= ~(IXON | IXOFF | IXANY); //无流量控制
opt.c_iflag &= ~(INLCR|ICRNL|BRKINT|IXON);
opt.c_lflag &= ~(ECHONL|ECHO|IEXTEN|ISIG|ICANON);
opt.c_oflag &= ~OPOST;
tcflush(fd, TCIOFLUSH);
opt.c_cc[VTIME] = 150;
opt.c_cc[VMIN] = 0;
if(tcsetattr(fd, TCSANOW, &opt) != 0)
{
perror("serial error");
return -1;
}
printf("configure completen");
printf("start send and receive datan");
while(1)
{
char read_buf[16];
char write_buf[5];
bzero(read_buf,16);
bzero(write_buf,4);
write_buf[0]=255;
write_buf[1]=255;
write_buf[2]=71;
write_buf[3]=77;
write_buf[4]='';
for(i=0;i
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
main()
{
int fd;
int i,ret;
int readcount;
int n = 0;
FILE* fp = NULL;
struct timeval tv;
fd_set rdfds;
if((fp=fopen("/dev/ttyUSB0","rb+"))==NULL)
{
perror("error");
return -1;
}
setbuf(fp,NULL);
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK); //默认为阻塞读方式
if(fd == -1)
{
perror("open serial n");
exit(0);
}
struct termios opt,old_termios;
tcgetattr(fd,&old_termios);
bzero(&opt,sizeof(opt));
cfsetispeed(&opt, B38400);
cfsetospeed(&opt, B38400);
opt.c_cflag |= (CLOCAL | CREAD);
opt.c_cflag &= ~CSIZE; //屏蔽字符大小位
opt.c_cflag |= CS8; //使用8位数据位
opt.c_cflag &= ~PARENB;
opt.c_cflag &= ~INPCK; //无奇偶校验
opt.c_cflag &= ~CSTOPB; //1位停止位
opt.c_cflag &= ~CRTSCTS;
opt.c_cflag &= ~(IXON | IXOFF | IXANY); //无流量控制
opt.c_iflag &= ~(INLCR|ICRNL|BRKINT|IXON);
opt.c_lflag &= ~(ECHONL|ECHO|IEXTEN|ISIG|ICANON);
opt.c_oflag &= ~OPOST;
tcflush(fd, TCIOFLUSH);
opt.c_cc[VTIME] = 150;
opt.c_cc[VMIN] = 0;
if(tcsetattr(fd, TCSANOW, &opt) != 0)
{
perror("serial error");
return -1;
}
printf("configure completen");
printf("start send and receive datan");
while(1)
{
char read_buf[16];
char write_buf[5];
bzero(read_buf,16);
bzero(write_buf,4);
write_buf[0]=255;
write_buf[1]=255;
write_buf[2]=71;
write_buf[3]=77;
write_buf[4]='';
for(i=0;i