谷歌开源serialPort api
按照步骤将SerialPort、jni、jnilibs加入,在build.gradle中添加
sourceSets {
main { jni.srcDirs = [] }
}
SerialPort serialPort = new SerialPort(new File(path),baudrate,0);
这里path是指串口文件地址、baudrate是指波特率,flags读写权限,
打开失败的情况可能是没有给权限,
进入ADB SHELL之后,cd /dev 进入dev后,ls查看设备是否有ttyS0 1 2 3等串口
输入:setenforce 0 关闭防火墙
输入:chmod 777 /dev/ttyS2(串口文件) 修改权限
这样的权限只是暂时的每次开机都要重新输入
SerialPort类里面的这行代码 //通过挂载到linux的方式,修改文件的操作权限 Process su = Runtime.getRuntime().exec("/system/xbin/su");
5.1以后好像是不能用了,所以最好还是驱动那边,帮忙把ttyS1的读写权限在开机的时候就给出来
串口接收数据往往需要的是16进制字符串命令,例如
String hexStr ="";
hexStr="03111111111FFFF07";
//16进制字符串转成byte[]直接发送就可以了
try {
byte[] bytes = hexString2Bytes(hexStr);
Logger.e("sendSerialPort:bytes"+hexStr);
sendSerialPort(bytes);
} catch (Exception e) {
e.printStackTrace();
}
/*
* 16进制字符串转字节数组
*/
public static byte[] hexString2Bytes(String hex) {
if ((hex == null) || (hex.equals(""))) {
return null;
} else if (hex.length() % 2 != 0) {
return null;
} else {
hex = hex.toUpperCase();
int len = hex.length() / 2;
byte[] b = new byte[len];
char[] hc = hex.toCharArray();
for (int i = 0; i < len; i++) {
int p = 2 * i;
b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p + 1]));
}
return b;
}
}