Android之USB转串口通信

本文介绍如何实现STM32通过USB转串口向Android设备发送数据,并在Android应用中显示。内容包括STM32的数据发送程序,以及Android应用的manifest.xml和usb_device_filter.xml配置。特别指出,此方案适用于使用CH340芯片的USB转串口设备,参考项目包括PhysicaloidLibrary和usb-serial-for-android。
摘要由CSDN通过智能技术生成

实验目的:

STM32通过USB转串口向Android Device持续发送数据,并让其显示在Android DeviceEditview界面上


manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dai.usb_test">

    <uses-feature android:name="android.hardware.usb.host"></uses-feature>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".UsbTestActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/usb_device_filter" />
        </activity>
    </application>

</manifest><strong>
</strong>


xml/usb_device_filter.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <usb-device  vendor-id="6790" product-id="29987"  />
</resources>

注:vendor-id和product-id都为十进制数值;



USB_Admin:

package com.example.dai.usb_test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by DAI on 2016/1/23.
 * Author:Will Smith
 * Email:15997135562@163.com
 *
 * Tip:
 *before developing USB on Android,you should configure manifests
 * accoriding to Android Developer
 */
public class USB_Admin {

    private UsbManager usbManager;
    private UsbDevice usbDevice;
    private UsbInterface usbInterface;
    private UsbEndpoint usbEndpointIn;
    private UsbEndpoint usbEndpointOut;
    private UsbDeviceConnection usbDeviceConnection;

    private static int TIMEOUT = 5000;

    /*自己编写的USB管理类的构造函数*/
    public USB_Admin(Context context){

        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        Log.v("USBManager:","" + usbManager);
    }

    /*****************************USB相关的操作**********************************/

    /*获得USB的usbManager*/
    public UsbManager get_UsbManager(){

        return usbManager;
    }


    /*获得
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 设备接收数据。
评论 45
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值