Android之USB转串口通信-基本流程

本文记录了在Android项目中使用USB转串口通信的流程,涉及kotlin语言和第三方库usb-serial-for-android。重点是配置ProlificSerialDriver的参数,如波特率、数据位、停止位和奇偶校验,以及避免配置中的陷阱。提供了一个USBSerialPortManager工具类的核心代码示例,适用于多数情况。
摘要由CSDN通过智能技术生成

背景:近期公司一个项目对接第三方支付设备(类似平板的设备外接usb转串口设备),需要使用usb转串口,实现通信和交互,今天记下过程。

有引用这个库 https://github.com/mik3y/usb-serial-for-android,感谢开源的大佬。

这个库已经集合了一般的芯片协议,就不需要自己再配置了。我们设备是用的ProlificSerialDriver.

唯一要注意的是配置设备的参数:波特率,数据位,体制位,奇偶校验等。其中我就在奇偶校验的参数配置上坑了一把。

只需要按照流程,注意些细节就能跑。

贴下核心的几段代码:

import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber

class ZYDataSource(){
    var mUsbSeriaPortManager: USBSerialPortManager? = null
    private var usbDeviceConnection: UsbDeviceConnection? = null
    private var mDevice: UsbDevice? = null
    private var mUsbSerialPort: UsbSerialPort? = null
    private var usbPermissionReceiver: UsbPermissionReceiver? = null

    private var mUsbManager: UsbManager? = null
    
    /**
    * 初始化
    */
    override fun initCompletable(context: Context): Completable {
        return Completable.create() {
            mUsbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
            //查找所有设备
            val driversList = Usb
Android 实现 USB 串口通信的具体步骤如下: 1. 获取 USB 设备的权限:在 AndroidManifest.xml 文件中添加一个 USB 设备的 intent-filter,并在应用程序中注册一个 BroadcastReceiver 来接收 USB 设备的插入和移除事件。 2. 扫描 USB 设备:使用 UsbManager 类扫描 USB 设备并获取其接口和端点信息。 3. 打开 USB 连接:使用 UsbDeviceConnection 类打开 USB 连接。 4. 配置串口参数:使用 UsbDeviceConnection 类设置串口参数,例如波特率、数据位、停止位和校验位等。 5. 发送和接收数据:使用 UsbDeviceConnection 类向 USB 设备发送数据并从 USB 设备接收数据。 下面是一个基本的示例代码,演示如何实现 Android USB 串口通信: ```java public class MainActivity extends Activity { private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"; private UsbManager mUsbManager; private UsbDevice mDevice; private UsbDeviceConnection mConnection; private UsbEndpoint mEndpointIn; private UsbEndpoint mEndpointOut; private BroadcastReceiver mUsbReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); // 注册 USB 设备插入和移除的 Broadcast Receiver mUsbReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { if (device != null) { // 权限已授予,打开 USB 连接 openUsbDevice(device); } } else { // 权限未授予 Log.d("USB", "permission denied for device " + device); } } } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { // USB 设备已插入,请求权限 UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); requestUsbPermission(device); } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { // USB 设备已移除,关闭连接 closeUsbDevice(); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_USB_PERMISSION); filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); registerReceiver(mUsbReceiver, filter); // 扫描 USB 设备并请求权限 UsbDevice device = findUsbDevice(); if (device != null) { requestUsbPermission(device); } } @Override protected void onDestroy() { super.onDestroy(); // 关闭连接和释放资源 unregisterReceiver(mUsbReceiver); closeUsbDevice(); } private UsbDevice findUsbDevice() { // 扫描 USB 设备并返回第一个串口设备 for (UsbDevice device : mUsbManager.getDeviceList().values()) { int interfaceCount = device.getInterfaceCount(); for (int i = 0; i < interfaceCount; i++) { UsbInterface usbInterface = device.getInterface(i); if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_COMM) { return device; } } } return null; } private void requestUsbPermission(UsbDevice device) { // 请求 USB 设备权限 PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); mUsbManager.requestPermission(device, permissionIntent); } private void openUsbDevice(UsbDevice device) { // 打开 USB 连接并设置端点信息 mDevice = device; mConnection = mUsbManager.openDevice(device); if (mConnection != null) { UsbInterface usbInterface = device.getInterface(0); for (int i = 0; i < usbInterface.getEndpointCount(); i++) { UsbEndpoint endpoint = usbInterface.getEndpoint(i); if (endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) { mEndpointIn = endpoint; } else if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) { mEndpointOut = endpoint; } } } } } private void closeUsbDevice() { // 关闭 USB 连接和释放资源 mDevice = null; if (mConnection != null) { mConnection.close(); mConnection = null; } mEndpointIn = null; mEndpointOut = null; } private void sendData(byte[] data) { // 发送数据到 USB 设备 if (mConnection != null && mEndpointOut != null) { mConnection.bulkTransfer(mEndpointOut, data, data.length, 0); } } private byte[] receiveData() { // 接收数据从 USB 设备 if (mConnection != null && mEndpointIn != null) { byte[] buffer = new byte[1024]; int count = mConnection.bulkTransfer(mEndpointIn, buffer, buffer.length, 0); if (count > 0) { byte[] data = new byte[count]; System.arraycopy(buffer, 0, data, 0, count); return data; } } return null; } } ``` 在上述示例代码中,我们使用 UsbManager 类扫描 USB 设备并获取其接口和端点信息。然后,我们使用 UsbDeviceConnection 类打开 USB 连接,并设置串口参数。最后,我们使用 UsbDeviceConnection 类向 USB 设备发送数据并从 USB 设备接收数据。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值