Android project combat (forty-five): Usb to serial communication (CH34xUARTDriver)

Original: Android project combat (forty-five): Usb to serial communication (CH34xUARTDriver)

The requirements are: insert a hardware into the usb interface of the mobile phone, and obtain data from the hardware

 For example : the mobile phone usb is inserted into the hardware A, A obtains the data of the devices a and b through the Bluetooth communication, and acts as a transfer station (which can do some data processing) to transmit the data (generated by the devices a and b) to the mobile phone program.

             Device A can also be a sensor itself, and it will generate data and transmit it to the mobile phone program.

 Applies to : The program needs data from some sensors, but the phone itself does not support (or cannot obtain it).

    There is a problem with the Bluetooth connection of the mobile phone itself (instability caused by the modification of the bottom layer of the manufacturer's Bluetooth, multiple connections cannot be made)

 Disadvantages : Some mobile phones do not support OTG, that is, the data of the hardware connected to the usb interface cannot be obtained.

 

-------------------------------------------------- -------Dividing line----------------------------------------- ---------------------

 

This article takes CH34X chip as an example.

Official: http://www.wch.cn/download/CH341SER_ANDROID_ZIP.html

 

  The official demo is an eclipse project, you need to create an android studio demo by yourself

   1. Create an android studio project

   2. Put the CH34xUARTDriver.jar file in the directory: app --> libs file

      

     Right click on the jar package

  

  3. Create a new xml folder under the res file, and copy the device_filter.xml in the official demo into it

  

 

      And add the code in the AndroidManifest.xml file:

        It is declared in an Activity that when the user inserts the device, it will prompt whether to open the program and transfer to the specified Activity ( this step is not necessary. , you don't need to do this step )

            <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/device_filter" />
 

 

   

   Fourth, some methods provided by the jar package

   //打开设备 
   public void OpenDevice(android.hardware.usb.UsbDevice usbDevice) { /* compiled code */ }

    // Close the device 
    public  void CloseDevice() { /* compiled code */ }
    
    // Determine whether the system supports USB HOST 
    public  boolean UsbFeatureSupported() { /* compiled code */ }
   
    public int ResumeUsbList() { /* compiled code */ }

    public int ResumeUsbPermission() { /* compiled code */ }

    // Determine whether the device is connected (insert usb interface) 
    public  boolean isConnected() { /* compiled code */ }
   
    protected android.hardware.usb.UsbDevice getUsbDevice() { /* compiled code */ }

    // Initialize the serial port device 
    public  boolean UartInit() { /* compiled code */ }
    
    // Configure the serial port baud rate, the function description can refer to the programming manual 
    public  boolean SetConfig( int i, byte b, byte b1, byte b2, byte b3) { /* compiled code */ }
    
    // Read serial port data 
    public  int ReadData( byte [] bytes, int i) { /* compiled code */ }
    
    // Write serial port data 
    public  int WriteData( byte [] bytes, int i) { /* compiled code */ }

    // Write serial port data 
    public  int WriteData( byte [] bytes, int i, int i1) { /* compiled code */ }

 

 

 5. Some pits encountered in practice (key points)

    1. When the hardware engineer sends and processes the hardware data of the usb serial port, the length of the data cannot be arbitrarily specified.

            The length of the pro-test data is 32, which is correct, and the program read() method accepts it normally, that is, 16, 32, and 64. . . . , if the length is 28 or 34, the data read by the program read() method is abnormal.

 

      2. The parameter of the write() method is a byte[] array, that is to say, if a string is input on the interface, the string needs to be converted into a byte[] array.

    The method in the official demo is incorrect, the correct one is provided as follows

/**
     * Convert String to byte[] array
     * @param arg
     * String object to be converted
     * @return converted byte[] array
      */ 
    private  byte [] toByteArray2(String arg) {
         if (arg != null ) {
             /* 1. First remove the ' ' in String, and then convert String to char array * / 
            char [] NewArray = new  char [1000 ];
             char [] array = arg.toCharArray();
             int length = 0 ;
             for ( int i = 0; i < array.length; i++ ) {
                 if (array[i] != ' ' ) {
                    NewArray[length] = array[i];
                    length++;
                }
            }
            NewArray[length] = 0x0D;
            NewArray[length + 1] = 0x0A;
            length += 2;

            byte[] byteArray = new byte[length];
            for (int i = 0; i < length; i++) {
                byteArray[i] = (byte)NewArray[i];
            }
            return byteArray;
        }
        return new byte[] {};
    }
Convert String to byte[] array

           

           Similarly, provide the following methods that may be used in project practice:

 public byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }
Intercept a part of the byte[] array

 

    /**
     * Convert byte[] array to String type
     * @param arg
     * The byte[] array that needs to be converted
     * @param length
     * The length of the array to be converted
     * @return converted String formation
      */ 
    private String toHexString( byte [] arg, int length) {
        String result = new String();
        if (arg != null) {
            for (int i = 0; i < length; i++) {
                if (i==length-1){
                    result = result
                            + (Integer.toHexString(
                            arg[i] < 0 ? arg[i] + 256 : arg[i]).length() == 1 ? "0"
                            + Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                            : arg [i])
                            : Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                            : arg[i])) + "";
                }else {
                    result = result
                            + (Integer.toHexString(
                            arg[i] < 0 ? arg[i] + 256 : arg[i]).length() == 1 ? "0"
                            + Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                            : arg [i])
                            : Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                            : arg[i])) + " ";
                }
            }
            return result;
        }
        return "";
    }
Convert byte[] array to String type

 

       3. The monitoring of the USB serial port plug-in operation is written in the jar package. If you need to customize it, you need to modify the source code of the jar package yourself.

       

       4. The operation in the third step is not necessary, you can decide whether to add it according to your needs

 

       5. Not all mobile phones support usb serial communication (does not support OTG function)

 

       6. The process is to open the device --> configure the device, if the configuration parameters are modified, you can configure the device directly without executing close -- > open > config

 

 6. Android studio Demo link

 

-------------------------------------------------- -------Dividing line----------------------------------------- ---------------------

 

For Bluetooth communication, usb serial communication, unity and Android communication, etc., please join the QQ group on the right for consultation.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325112635&siteId=291194637