如何读取和写入Android中的COM /串行端口的数据?

pik*_*iks 12 java android javax.comm

我必须使用android读取和写入设备的COM端口数据,我正在使用javax.comm包但是当我安装apk文件时,它没有显示设备的任何端口所以是否有任何权限我需要在清单文件中添加?

gob*_*dor 21

您的问题与操作系统有关.Android在Linux下运行Linux,Linux对待串口的方式与Windows不同.javax.comm还包含win32com.dll一个驱动程序文件,您将无法在Android设备上安装该文件.如果您确实找到了实现目标的方法,那么您实际上无法在Linux环境中查找"COM"端口.串口将使用不同的名称.

 Windows Com Port   Linux equivalent  
      COM 1           /dev/ttyS0  
      COM 2           /dev/ttyS1
      COM 3           /dev/ttyS2 
Run Code Online (Sandbox Code Playgroud)

所以,假设,如果你的想法有效,你必须寻找这些名字.

幸运的是,Android确实有与USB设备连接的规定(我假设你要连接到它,而不是并行或RS-232端口).为此,您需要将设备设置为USB主机.这是你想要做的:

  1. 得到一个USBManager.
  2. 找到你的设备.
  3. 得到USBInterfaceUSBEndpoint.
  4. 打开连接.
  5. 传输数据.

这是我对你如何做的粗略估计.当然,您的代码将具有更成熟的处理方式.

String YOUR_DEVICE_NAME;
byte[] DATA;
int TIMEOUT;

USBManager manager = getApplicationContext().getSystemService(Context.USB_SERVICE);
Map<String, USBDevice> devices = manager.getDeviceList();
USBDevice mDevice = devices.get(YOUR_DEVICE_NAME);
USBDeviceConnection connection = manager.openDevice(mDevice);
USBEndpoint endpoint = device.getInterface(0).getEndpoint(0);

connection.claimInterface(device.getInterface(0), true);
connection.bulkTransfer(endpoint, DATA, DATA.length, TIMEOUT);
Run Code Online (Sandbox Code Playgroud)

额外的材料为您的阅读乐趣:http://developer.android.com/guide/topics/connectivity/usb/host.html


小智 6

我不是专家,但对于所有想要连接串行 RS-232 端口或打开串行端口但无法通过 找到设备的人UsbManager,您可以使用如下方法找到所有设备:

mDrivers = new Vector<Driver>();
LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
String l;
while ((l = r.readLine()) != null) {
    String drivername = l.substring(0, 0x15).trim();
    String[] w = l.split(" +");
    if ((w.length >= 5) && (w[w.length - 1].equals("serial"))) {
        mDrivers.add(new Driver(drivername, w[w.length - 4]));
    }
}
Run Code Online (Sandbox Code Playgroud)

找到所有驱动程序后,迭代所有驱动程序以获取所有设备,使用如下所示:

mDevices = new Vector<File>();
File dev = new File("/dev");

File[] files = dev.listFiles();


if (files != null) {
    int i;
    for (i = 0; i < files.length; i++) {
        if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
            Log.d(TAG, "Found new device: " + files[i]);
            mDevices.add(files[i]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是Driver类构造函数,有两个成员变量:

public Driver(String name, String root) {
    mDriverName = name;
    mDeviceRoot = root;
}
Run Code Online (Sandbox Code Playgroud)

要打开串行端口,您可以使用Android SerialPort API。只需打开设备上的串行端口即可write。(你必须知道你的设备路径和波特率。例如我的设备是ttyMt2,波特率96000。)

int baudRate = Integer.parseInt("96000");
mSerialPort = new SerialPort(mDevice.getPath(), baudRate, 0);
mOutputStream = mSerialPort.getOutputStream();
byte[] bytes = hexStr2bytes("31CE");
mOutputStream.write(bytes);
Run Code Online (Sandbox Code Playgroud)

您可以从https://github.com/licheedev/Android-SerialPort-Tool下载完整的项目,而不是在此代码上浪费时间。