[关闭]
@Tyhj 2018-12-27T11:17:22.000000Z 字数 947 阅读 1332

Android串口通信工具

Android


Android串口通信简单封装,可以用于和连接串口的硬件通信或者进行硬件调试

集成方法:

Step 1. Add the JitPack repository to your build file

  1. //Add it in your root build.gradle at the end of repositories:
  2. allprojects {
  3. repositories {
  4. ...
  5. maven { url 'https://jitpack.io' }
  6. }
  7. }

Step 2. Add the dependency

  1. //Add the dependency
  2. dependencies {
  3. implementation 'com.github.tyhjh:SerialPortUtil:1.0.0'
  4. }

调用方法

读取文件权限应该是需要的

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

获取所有串口地址

  1. String[] devicesPath = new SerialPortFinder().getDevicesPaths();

打开串口,设置读取返回数据超时时间

  1. SerialPortService serialPortService = new SerialPortBuilder()
  2. .setTimeOut(100L)
  3. .setBaudrate(9600)
  4. .setDevicePath("dev/ttyS4")
  5. .createService();

发送指令

  1. //发送byte数组数据
  2. byte[] receiveData = serialPortService.sendData(new byte[2]);
  3. //发送16进制的字符串
  4. byte[] receiveData = serialPortService.sendData("55AA0101010002");
  5. Log.e("MainActivity:", ByteStringUtil.byteArrayToHexStr(receiveData));

打开或者关闭日志,默认关闭

  1. serialPortService.isOutputLog(true);

项目源码:https://github.com/tyhjh/SerialPortUtil

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注