温馨提示×

Android串口如何发送数据

小樊
124
2024-08-03 04:44:14
栏目: 编程语言

要在Android设备上通过串口发送数据,可以使用Java中的SerialPort类来实现。以下是一个简单的示例代码,演示如何在Android设备上通过串口发送数据:

import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

public class SerialPortSender {

    private UsbDeviceConnection connection;
    private OutputStream outputStream;

    public SerialPortSender(UsbDeviceConnection connection) {
        this.connection = connection;
        this.outputStream = connection.openOutputStream();
    }

    public void sendData(byte[] data) {
        try {
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static UsbDeviceConnection findSerialPortConnection(UsbManager usbManager) {
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        UsbDeviceConnection connection = null;
        
        for (UsbDevice device : deviceList.values()) {
            if (device.getVendorId() == VENDOR_ID && device.getProductId() == PRODUCT_ID) {
                connection = usbManager.openDevice(device);
                break;
            }
        }
        
        return connection;
    }
}

在上面的代码中,SerialPortSender类负责实现与串口的连接和数据发送功能。sendData方法用于发送数据,findSerialPortConnection方法用于查找串口连接。要使用该类,可以在Android应用的主活动中进行调用:

UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbDeviceConnection connection = SerialPortSender.findSerialPortConnection(usbManager);

if (connection != null) {
    SerialPortSender sender = new SerialPortSender(connection);
    byte[] data = "Hello, world!".getBytes();
    sender.sendData(data);
} else {
    Log.e(TAG, "Cannot find serial port connection");
}

在上面的代码中,首先通过UsbManager获取USB设备管理器实例,然后通过findSerialPortConnection方法查找串口连接。如果找到了串口连接,就可以实例化SerialPortSender类,并通过sendData方法发送数据。

0