Android串口通信簡(jiǎn)單封裝,可以用于和連接串口的硬件通信或者進(jìn)行硬件調(diào)試
集成方法:
Step 1. Add the JitPack repository to your build file
//Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
//Add the dependency
dependencies {
implementation 'com.github.tyhjh:SerialPortUtil:1.0.0'
}
調(diào)用方法
讀取文件權(quán)限應(yīng)該是需要的
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
獲取所有串口地址
String[] devicesPath = new SerialPortFinder().getDevicesPaths();
打開(kāi)串口,設(shè)置讀取返回?cái)?shù)據(jù)超時(shí)時(shí)間
SerialPortService serialPortService = new SerialPortBuilder()
.setTimeOut(100L)
.setBaudrate(9600)
.setDevicePath("dev/ttyS4")
.createService();
發(fā)送指令
//發(fā)送byte數(shù)組數(shù)據(jù)
byte[] receiveData = serialPortService.sendData(new byte[2]);
//發(fā)送16進(jìn)制的字符串
byte[] receiveData = serialPortService.sendData("55AA0101010002");
Log.e("MainActivity:", ByteStringUtil.byteArrayToHexStr(receiveData));
打開(kāi)或者關(guān)閉日志,默認(rèn)關(guān)閉
serialPortService.isOutputLog(true);
//關(guān)閉串口
serialPortService.close();
項(xiàng)目源碼:https://github.com/tyhjh/SerialPortUtil