Android USB to serial port communication development basic process

Source: Internet
Author: User

Long time no article, years ago, the company opened a new project, and USB to the serial port communication related, the demand is the Android tablet through the USB adapter and several peripherals to communicate, has been busy to the recent, just slowly idle down, while this weekend is not busy, recording the basic flow of USB to serial communication development.

We developed the use of USB host mode, namely: Android tablet as a host, USB peripherals as a slave for data communication. The entire development process can be summed up in the following points:

1. Discover the device

UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);Map<String, UsbDevice> usbList = usbManager.getDeviceList();

By usbmanager the class provided by this system, we can enumerate all the USB devices currently connected, we mainly need the Usbdevice object, about Usbdevice This class, the official comment:

This class represents a USB device attached to the android device with the android device acting as the USB host.

Yes, this class represents the USB device that Android is connected to.

2. Turn on the device

Next, we need to open the newly-found USB device, we can think of the connection between the tablet and the USB peripheral as a channel, only the channel door open, both sides to communicate.

In general, when you first access a USB device on a custom Android device, we don't have access rights by default, so let's first determine if there's access to the Usbdevice you're currently opening:

if (!usbManager.hasPermission(usbDevice)) {       usbPermissionReceiver = new UsbPermissionReceiver();       //申请权限       Intent intent = new Intent(ACTION_DEVICE_PERMISSION);       PendingIntent mPermissionIntent = PendingIntent.getBroadcast(context, 0, intent, 0);       IntentFilter permissionFilter = new IntentFilter(ACTION_DEVICE_PERMISSION);       context.registerReceiver(usbPermissionReceiver, permissionFilter);       usbManager.requestPermission(usbDevice, mPermissionIntent);        }

Here we declare a broadcast usbpermissionreceiver to do some other processing after receiving the broadcast of a successful authorization:

  private class UsbPermissionReceiver extends BroadcastReceiver {        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            if (ACTION_DEVICE_PERMISSION.equals(action)) {                synchronized (this) {                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);                    if (device.getDeviceName().equals(usbDevice.getDeviceName()) {                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {                          //授权成功,在这里进行打开设备操作                        } else {                          //授权失败                        }                    }                }            }        }    }

Next, we want to find the interface with data transmission function usbinterface, from its edge to find data input and output port Usbendpoint, generally, a usbdevice has multiple usbinterface, we need is generally the first one, so:

usbInterface=usbDevice.getInterface(0);

Similarly, a usbinterface has multiple usbendpoint, control ports and data ports, so we need to find the data input and output two ports we need based on type and data flow:

for (int index = 0; index < usbInterface.getEndpointCount(); index++) {                UsbEndpoint point = usbInterface.getEndpoint(index);                if (point.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {                    if (point.getDirection() == UsbConstants.USB_DIR_IN) {                        usbEndpointIn = point;                    } else if (point.getDirection() == UsbConstants.USB_DIR_OUT) {                        usbEndpointOut = point;                    }                }            }

Finally, is the real open USB device, we need to establish a usbdeviceconnection with the USB peripheral, its annotations are very brief description of its purpose:

This class is used for sending and receiving data and control messages to a USB device.

It's also very easy to get, just a code:

usbDeviceConnection = usbManager.openDevice(usbDevice);

Here, theoretically the connection between the tablet and USB peripherals has been established, but also can start data, but most of us also need to do some configuration of the USB serial port, such as baud rate, stop bit, data control, or otherwise the configuration of the two sides, the data received will be garbled. Specifically how to configure, you use the serial chip is what, the current popular have pl2303,ch340, due to the length of the problem, need to configure the serial code of the friend private messages I I sent to you.

3. Data transfer

Here, we have been able to communicate with the USB peripherals, first of all to see how to send data to the USB device.

 1.向usb外设发送数据

In the second step, we have obtained the output port of the data usbendpointin, we send the data to the peripheral through this port to achieve. To see how to use:

int ret = usbDeviceConnection.bulkTransfer(usbEndpointOut, data, data.length, DEFAULT_TIMEOUT);

Bulktransfer This function is used for data transmission on a given port, the first parameter is the port of this transmission, here we use the output port, the second parameter is the data to be sent, the type is a byte array, the third parameter represents the length of the data to be sent, the last parameter is the timeout, The return value represents the number of bytes sent successfully, and if 1 is returned, the send fails.

2.接受usb外设发送来的数据

Similarly, we have found the data input port Usbendpointin, because the input of the data is not timed, so we can open another thread to specifically accept the data, the code to accept the data is as follows:

int inMax = inEndpoint.getMaxPacketSize(); ByteBuffer byteBuffer = ByteBuffer.allocate(inMax); UsbRequest usbRequest = new UsbRequest(); usbRequest.initialize(connection, inEndpoint); usbRequest.queue(byteBuffer, inMax); if(connection.requestWait() == usbRequest){     byte[] retData = byteBuffer.array();     for(Byte byte1 : retData){         System.err.println(byte1);     } }

Above, is the basic process of USB to serial communication, some places are not very comprehensive, such as the method of receiving USB peripheral data should have other, the shortcomings are welcome to correct.

Android USB to serial port communication development basic process

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.