allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
添加依赖
dependencies {
implementation 'com.github.mik3y:usb-serial-for-android:2.2.2'
}
添加权限
如果需要Android检测到设备的插入,则需要在res/xml/
下添加 device_filter.xml,CH340官网下载的工程Demo内也有。 并要在AndroidManifest
中补全代码
使用
USB模块的初始化
UsbSerialPort temperaturePort;
SerialInputOutputManager serialInputOutputManager;
ExecutorService mExecutor = Executors.newSingleThreadExecutor();
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
if (manager != null) {
List availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
if (!availableDrivers.isEmpty()) {
UsbSerialDriver driver = availableDrivers.get(0);
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
if (connection != null) {
temperaturePort = driver.getPorts().get(0);
try {
temperaturePort.open(connection);
//四个参数分别是:波特率,数据位,停止位,校验位
temperaturePort.setParameters(9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
temperaturePort.setRTS(true);
temperaturePort.setDTR(true);
serialInputOutputManager = new SerialInputOutputManager(temperaturePort, mListener);
mExecutor.submit(serialInputOutputManager);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
发送数据
temperaturePort.write(Str16ToBytes("01 03 00 00 00 01 84 0A", " "), 200);
/**
* 16进制字符串转byte数组
*
* @param str 需要转换的字符串
* @param splitChare 中断间隔符
* @return 转换好的byte[]数组
*/
public byte[] Str16ToBytes(String str, String splitChare) {
String[] string = str.trim().split(splitChare);
byte[] bytes = new byte[string.length];
for (int i = 0; i < string.length; i++) {
bytes[i] = (byte) (Integer.parseInt(string[i], 16) & 0xff);
}
return bytes;
}
监听和接收数据
SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() {
@Override
public void onNewData(byte[] data) {
String[] dataStrings = BytesToStrs16(data);
}
@Override
public void onRunError(Exception e) {
e.printStackTrace();
}
};
/**
* 十进制bytes转16进制strings
*
* @param bytes 十进制bytes
* @return 16进制strings
*/
public String[] BytesToStrs16(byte[] bytes) {
String[] strs = new String[bytes.length];
for (int i = 0; i < bytes.length; i++) {
strs[i] = Integer.toHexString(bytes[i] & 0xff);
}
return strs;
}
待解决问题
插着传感器通电启动后,能检测到设备但是无法打开Port,暂时不确定什么原因