我是靠谱客的博主 沉默钢铁侠,最近开发中收集的这篇文章主要介绍android 5.1 设备上使用 usb2com 时 【 tcgetattr() failed 】 错误问题解决,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
先利用Android 源码编译一个小测试程序:
//test_tty.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <pthread.h>
#include <string.h>
#include <stdbool.h>
#include <termios.h>
//#include <cutils/Log.h>
//#include <utils/Log.h>
//#define
LOG_TAG
"test_tty"
#define READLENTH 256
int uartOpen(char *uartDevicePath,int speed,int dataWidth,int nstopBit)
{
//Info
int fd=-1;
struct termios new_cfg,old_cfg;
printf("uart path=%sn",uartDevicePath);
//open device
fd=open(uartDevicePath,O_RDWR | O_NOCTTY );
if(fd==-1){
printf("open failed!n");
return -1;
}
//preserve the old configuration
if(tcgetattr(fd,&old_cfg)!=0){
printf("Old config preserve failed!n");
return -1;
}
//set mode
new_cfg.c_cflag |=CLOCAL |CREAD;
//set baudrate
switch(speed){
case 1800:{
cfsetispeed(&new_cfg,B1800);
cfsetospeed(&new_cfg,B1800);
}break;
case 2400:{
cfsetispeed(&new_cfg,B2400);
cfsetospeed(&new_cfg,B2400);
}break;
case 4800:{
cfsetispeed(&new_cfg,B4800);
cfsetospeed(&new_cfg,B4800);
}break;
case 9600:{
cfsetispeed(&new_cfg,B9600);
cfsetospeed(&new_cfg,B9600);
}break;
case 19200:{
cfsetispeed(&new_cfg,B19200);
cfsetospeed(&new_cfg,B19200);
}break;
case 38400:{
cfsetispeed(&new_cfg,B38400);
cfsetospeed(&new_cfg,B38400);
}break;
case 57600:{
cfsetispeed(&new_cfg,B57600);
cfsetospeed(&new_cfg,B57600);
}break;
case 115200:{
cfsetispeed(&new_cfg,B115200);
cfsetospeed(&new_cfg,B115200);
}break;
default:{
cfsetispeed(&new_cfg,B115200);
cfsetospeed(&new_cfg,B115200);
}break;
}
//set size of data
new_cfg.c_cflag &=~CSIZE;
switch(dataWidth){
case 5:{
new_cfg.c_cflag |=CS5;
}break;
case 6:{
new_cfg.c_cflag |=CS6;
}break;
case 7:{
new_cfg.c_cflag |=CS7;
}break;
case 8:{
new_cfg.c_cflag |=CS8;
}break;
default :{
new_cfg.c_cflag |=CS8;
}break;
}
//set stopbit
if(nstopBit == 2)
new_cfg.c_cflag |=(CSTOPB);
else if(nstopBit == 1)
new_cfg.c_cflag &=~(CSTOPB);
//set waittime out
new_cfg.c_cc[VTIME]=80;
// n * 100ms
new_cfg.c_cc[VMIN]=0;
//start
if(-1==tcsetattr(fd,TCSANOW,&new_cfg)){
printf("Uart setting failed!n");
return -1;
}
return fd;
}
int main(int argc, char *argv[])
{
char buff[READLENTH] = {'