实现的功能就是串口的自收自发功能我用的事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); }
}
}