USB、USB转串口、串口通信的区别与实现

Android如何监听USB插拔

全网独一无二的USB、USB转串口二合一通信SDK

USB通信使用系统api,USB转串口通信使用第三方库usb-serial-for-android,串口通信使用Google官方库android-serialport-api

一、USB通信

1.1 查找USB设备(2选1)

1.1.1 获取已连接USB设备

UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();

1.1.2 监听USB设备插拔
https://blog.csdn.net/u011630465/article/details/86525857?spm=1001.2014.3001.5501

1.2 USB设备授权

usb设备必须授权成功才能进行通信,否则会报设备没有权限错误。

// 判断usb设备是否有权限
manager.hasPermission(mUsbDevice)

// 为usb设备申请权限
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_DEVICE_PERMISSION), 0);
manager.requestPermission(mUsbDevice, pendingIntent)

1.3 打开USB设备

UsbDeviceConnection mConnection= manager.openDevice(mUsbDevice);

1.4 找到通信接口和节点

一般只有一个UsbInterface(也可能存在多个),每个UsbInterface下又有多个UsbEndpoint,找到对应的读写数据节点。

UsbInterface dataIface = mDevice.getInterface(0);
for (int i = 0; i < dataIface.getEndpointCount(); i++) {
    UsbEndpoint endpoint = dataIface.getEndpoint(i);
    if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) {
        mReadEndpoint = endpoint;
    }
    if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
        mWriteEndpoint = endpoint;
    }
}

1.5 开始通信

1.5.1 写数据

mConnection.bulkTransfer(mWriteEndpoint, bytes, bytes.length, timeout);

1.5.2 读数据

mConnection.bulkTransfer(mReadEndpoint, bytes, bytes.length, timeout);

二、USB转串口通信

USB转串口通信使用第三方库https://github.com/mik3y/usb-serial-for-android,底层实际也是使用系统USB通信api,在系统api的基础上增加串口驱动封装。

1.1-1.3(与USB通信流程一致)

1.4 检查驱动

驱动类型由串口芯片决定,驱动本质也只是调用系统usb写数据api完成一系列初始化操作。

UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(usbDevice);

1.5 打开串口,设置相关参数

UsbSerialPort mUsbSerialPort = driver.getPorts().get(mPort);
mUsbSerialPort.open(mConnection);
mUsbSerialPort.setParameters(mBaudRate, mDataBits, mStopBits, mParity);

1.6 开始通信

1.6.1 写数据

mUsbSerialPort.write(bytes, TIMEOUT);

1.6.2 读数据

mUsbSerialPort.read(bytes, TIMEOUT);

三、串口通信

串口通信使用google官方sdk:https://github.com/cepr/android-serialport-api

SerialPort mSerialPort = new SerialPort(new File("/dev/ttyUSB0"), 9600, 0);
// 读
InputStream inputStream = mSerialPort.getInputStream();
inputStream.read(buffer);
// 写
OutputStream outputStream = mSerialPort.getOutputStream();
out.write(bytes);
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值