作为一个工具篇,在后续工作中经常会用到串口测试工具,方便工作中作为测试工具使用。
文章目录
资料参考
串口的原理基本一致的,没有特别的东西,无论在哪里使用,顶多一层封装。
这里可以参考一下之前的笔记,framework层的应用
串口在framework层的应用
或者 网上太多的demo 封装,可参考下。
串口应用场景
- 串口,作为一种协议,使用场景无处不在。
- 我接触的在Android平台上外挂的各种模组通讯用到了串口:功放模组、物联网模组、话筒模组、语音模块模组、各种传感器模组、各种外围设备通讯…
代码分析
串口so文件的载入和配置

在 build.gradle 文件中配置 .so 库文件
ndk {
abiFilters 'armeabi','armeabi-v7a'
}
本地native 方法
使用到串口,核心三个方法,如下
- 加载.so 文件
- 打开串口
- 关闭串口
static {
System.loadLibrary("serial_port");
}
private native static FileDescriptor open(String path, int baudrate);
private native void close();
SerialPort 流封装方法
本地方法,最终通过流来和串口进行通讯的,下面给出 open 的具体操作,方法如下
public SerialPort(File device, int baudate) throws IOException {
if (!device.canRead() || !device.canWrite()) {
try {
Process su = Runtime.getRuntime().exec("su");
String cmd = "chmod 777 " + device.getAbsolutePath();
su.getOutputStream().write(cmd.getBytes());
su.getOutputStream().flush();
int waitFor = su.waitFor();
boolean canRead = device.canRead();
boolean canWrite = device.canWrite();
if (waitFor != 0 || !canRead || !canWrite) {
throw new SecurityException();
}
} catch (Exception e) {
e.printStackTrace();
}
}
mFd = open(device.getAbsolutePath(), baudate);
if (mFd == null) {
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}
其中 open 是native 方法,拿到了文件描述符,就可以进行 流操作了。
完整的SerialPort 代码如下:
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import

最低0.47元/天 解锁文章
2114

被折叠的 条评论
为什么被折叠?



