这可能是你需要的串口调试工具库

1,339 阅读2分钟

库源码在github.com/F1ReKing/An…

前言

最近几个月一直有持续在做跟硬件串口数据通信的项目,一开始用的是谷歌官方串口库android-serialport-api,简单地封装了接口,但硬件部门要求配置做下流控测试,但该项目仅支持串口名称及波特率,所以在谷歌项目的基础上添加支持数据位、数据位、停止位、流控等配置,想想还是整理下开源出来做下贡献,帮助下有需要的人。

此项目没做协议解析,协议解析部分要根据协议做分包处理。

依赖引入

Step 1. Add the JitPack repository to your build file

Add it in your root build.gradle at the end of repositories:

1allprojects {
2    repositories {
3        ...
4        maven { url 'https://jitpack.io' }
5    }
6}

Step 2. Add the dependency

1dependencies {
2        implementation 'com.github.F1ReKing:Android-SerialPort:1.1'
3}

使用

1. 查询串口列表

1SerialPortFinder#getDrivers();

2. 配置串口参数

1SerialPortHelper#Builder(String port, int baudRate).build(); //支持配置串口号,波特率(默认值115200)
2setStopBits(int stopBits); // 支持设置停止位 默认值为2
3setDataBits(int dataBits); // 支持设置数据位 默认值为8
4setParity(int parity); // 支持设置检验位 默认值为0
5setFlowCon(int flowCon); // 支持设置流控 默认值为0
6setFlags(int flags); // 支持设置标志 默认值为0,O_RDWR  读写方式打开

3. 打开串口

1SerialPortHelper#open();

4. 关闭串口

1SerialPortHelper#close();

4. 发送数据

1SerialPortHelper#sendBytes(byte[] bytes); // 支持发送byte[]
2SerialPortHelper#sendHex(String hex); // 支持发送Hex
3SerialPortHelper#sendTxt(String txt); // 支持发送ASCII码

5. 接收数据

1public interface ISerialPortDataListener {
2    // 接收数据回调
3    void onDataReceived(byte[] bytes);
4       // 发送数据回调
5    void onDataSend(byte[] bytes);
6}

6. 回调

1//  串口打开状态监听
2void setIOpenSerialPortListener(IOpenSerialPortListener IOpenSerialPortListener);
3
4// 串口消息监听
5void setISerialPortDataListener(ISerialPortDataListener ISerialPortDataListener);