2 qq 20835381 qq_20835381 于 2016.05.05 15:17 提问

linux串口编程实现自收自发功能发送可以发出去read读取总是返回-1

实现的功能就是串口的自收自发功能我用的事ch340 ch340的u口连接到笔记本上 ch340的串口端的rx 和tx用杜邦线连接在一起就是这样了但是现在问题是编译完成后发送可以发出去但是读取总是失败read返回值总是-1不知道哪里出错了求大神们解答下
小弟拜谢
#include
#include
#include
#include
#include

void set_speed(int, int);
int main()
{
int fd,flag,wr_num=0,rd_num=0;
struct termios term;
speed_t baud_rate_i,baud_rate_o;
char send_buf[]="hello,serial!",recv_buf[20];
fd=open("/dev/ttyUSB0",O_RDWR|O_NONBLOCK);
if(fd==-1)
printf("can not open the COM1!\n");
else
printf("open COM1 ok!\n");
flag=tcgetattr(fd,&term);
baud_rate_i=cfgetispeed(&term);
baud_rate_o=cfgetospeed(&term);
printf("杈撳叆娉㈢壒鐜囨槸%d锛岃緭鍑烘尝鐗圭巼鏄?d锛屾枃浠舵弿杩扮鏄?d\n",baud_rate_i,baud_rate_o,fd);
set_speed(fd,9600);
flag=tcgetattr(fd,&term);
baud_rate_i=cfgetispeed(&term);
baud_rate_o=cfgetospeed(&term);
printf("杈撳叆娉㈢壒鐜囨槸%d锛岃緭鍑烘尝鐗圭巼鏄?d锛屾枃浠舵弿杩扮鏄?d\n",baud_rate_i,baud_rate_o,fd);
while(1) { wr_num=write(fd,send_buf,sizeof(send_buf));/*鍏堝啓鍏?/
if(wr_num>0)
{
printf("write success!\n");
} else
{
printf("write fail!\n");
} sleep(1);
rd_num=read(fd,recv_buf,sizeof(recv_buf));/*鍐嶈鍑?/ if(rd_num>0)
{ printf("we can read \"%s\" from the COM1.total:%d characters\n",recv_buf,rd_num);
} else
{
printf("read fail!\n");
}

sleep(2); }
}

int speed_arr[] = {B38400, B19200, B9600, B4800, B2400, B1200, B300,
B38400, B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {38400, 19200, 9600, 4800, 2400, 1200, 300, 38400,
19200, 9600, 4800, 2400, 1200, 300, };

void set_speed(int fd, int speed)
{
int i;
int status;
struct termios Opt;
tcgetattr(fd, &Opt);
for ( i= 0; i < sizeof(speed_arr) / sizeof(int); i++)
{
if (speed == name_arr[i])
{

tcflush(fd, TCIOFLUSH);

cfsetispeed(&Opt, speed_arr[i]);
cfsetospeed(&Opt, speed_arr[i]);

status = tcsetattr(fd, TCSANOW, &Opt);
if (status != 0)
{ perror("tcsetattr fd1");
return; }

tcflush(fd,TCIOFLUSH); }
}
}

1个回答

qq_20835381
qq_20835381   2016.05.05 17:13

别沉啊我靠 求助大家啊 真的很急的啊

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!