本文介绍了使用usbSerialForAndroid库在android中进行串口通信。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在android中使用usbSerialForAndroid库进行串口通信。

在我的代码中,我已成功授予USB端口的读写权限。



我的问题是我第三次收到数据当我尝试从串口读取时,前两次我读取的数据是零字节。



是否有任何特定的设置需要进行读取并写入android中的串口。



我的示例代码在这里



I am using usbSerialForAndroid library for serial communication in android.
In my code i have successfully granted read and write permission on USB port.

My problem is "I receive the data on third time when i try to read from serial port, first two times i read the data received is zero bytes".

Is there any specific setting that needs to be done for reading and writing to serial ports in android.

My sample code is here

UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
                        List<usbserialdriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
                        UsbSerialDriver driver = availableDrivers.get(0);
                        UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
                        port = driver.getPorts().get(0);

                        try {

                            port.open(connection);
                            port.setParameters(9600, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
                            int usbResultOut, usbResultIn1, usbResultIn2, usbResultIn3;
                            String tOut = "S\r"  //This is the data i am sending to serial device.
                            byte[] bytesOut = tOut.getBytes(); //convert String to byte[]
                            byte[] bytesIn1 = new byte[25];
                            byte[] bytesIn2 = new byte[25];
                            byte[] bytesIn3 = new byte[25];

                            usbResultOut = port.write(bytesOut, 1000); //write the data to serial device.

                            usbResultIn1 = port.read(bytesIn1, 1000);  //read the data but in my case 0 bytes received.
                            usbResultIn2 = port.read(bytesIn2, 1000);  //read the data but in my case 0 bytes received.
                            usbResultIn3 = port.read(bytesIn3, 1000);  //read the data, this time the data is received.
}

推荐答案



这篇关于使用usbSerialForAndroid库在android中进行串口通信。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 16:13