linux USB 转串口

1. 内核配置

Device Drivers  --->

     [*] USB support  ---> 

          USB Serial Converter support  --->

                <*> USB Serial Converter support

                <*>   USB Prolific 2303 Single Port Serial Driver

 

2. 编译内核,嵌入式板子加载内核,进入内核后,查看是否生成对应的设备节点

#ls /dev/ttyUSB0

如果没有上述节点,手动创建

#mknod /dev/ttyUSB0 c 188 0

 

3. 编写程序,测试USB转串口是否能正常读写

 

int Test_com(char *pCom)
{
 fd_set fds_r;
 struct termios Opt;
 int fdtty0=0;
 struct timeval tm = {1, 0};
 int err=0;
 char readbuf = '0';
 char tmp[16] = {0};
 char buf1='t';
 char data1='s'; 
 
 fdtty0=open(pCom, O_SYNC | O_RDWR );//"/dev/ttyS2"
 if (fdtty0 < 0)
 {
  printf( "open %s failed!/n", pCom);
  goto ERR;
 }
 
 if (tcgetattr(fdtty0, &Opt) < 0)
  goto ERR;
 
 /* If you uncomment ISIG and BRKINT below, then ^C will be ignored.*/
 Opt.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG | ECHOE);
 Opt.c_iflag &= ~(ICRNL | INPCK | ISTRIP | IXON | BRKINT);
 Opt.c_iflag &= ~(CSIZE | PARENB | CSTOPB);
 Opt.c_oflag &= ~(ONLCR);//for not translate from NL to CR NL
 Opt.c_cflag = CS8 | B115200 | CLOCAL | CREAD;
 Opt.c_cc[VMIN] = 0;
 Opt.c_cc[VTIME] = 0;

 tcflush(fdtty0, TCIFLUSH);
 if(tcsetattr(fdtty0, TCSAFLUSH, &Opt) < 0)
  goto ERR;
 
 FD_ZERO(&fds_r);
 FD_SET(fdtty0, &fds_r);

 if(write(fdtty0, &buf1, 1) < 0)
 {
  printf("write version error/n");
  return 0;
 }
 
 err=select(fdtty0+1, &fds_r, NULL, NULL, &tm);
 
 if (err < 0)
 {  /* failure */
  printf("select Error/n");
 }
 else if (err == 0)
 {  /* time out; */
  printf("select Timeout/n");
 }
 
 if (FD_ISSET(fdtty0, &fds_r))
 {
  //err = read(fdtty0, &data1,1);
  
  err = read(fdtty0, tmp,sizeof(tmp));
  printf( "err: %d, tmp: %s/n" ,err,tmp );
  
  if (err < 0)
  {
   printf("read error/n");
  }
 }

ERR:
 if (fdtty0 > 0)
  close(fdtty0);
 fdtty0 = 0;
 
 if(buf1==tmp[0])
 {
  printf("buf1:%c,tmp[0]:%c, return 1/n",buf1,tmp[0]);  
  return 1;
 }
 else
 {
  printf("buf1:%c,tmp[0]:%c, return 0/n",buf1,tmp[0]);
  return 0;
 } 
}

 

 

你可能感兴趣的:(嵌入式linux)