Changing USB Baud Rate from 9600 to 115200 on Android

ilkengin picture ilkengin · Jul 14, 2014 · Viewed 12.4k times · Source

I have an Arduino which sends data serially in 115200 baud rate.

There is an application that receives data from Arduino in 9600 baud rate. The code is

    // Arduino USB serial converter setup
    // Set control line state
    mUsbConnection.controlTransfer(0x21, 0x22, 0, 0, null, 0, 0);
    // Set line encoding.
    mUsbConnection.controlTransfer(0x21, 0x20, 0, 0, getLineEncoding(9600), 7, 0);
    //mUsbConnection.controlTransfer(0x21, 0x20, 0x001A, 0, getLineEncoding(9600), 7, 0);

Then in the getLineEncoding() function

private byte[] getLineEncoding(int baudRate) {
    final byte[] lineEncodingRequest = { (byte) 0x80, 0x25, 0x00, 0x00, 0x00, 0x00, 0x08 };
    switch (baudRate) {
    case 14400:
        lineEncodingRequest[0] = 0x40;
        lineEncodingRequest[1] = 0x38;
        break;

    case 19200:
        lineEncodingRequest[0] = 0x00;
        lineEncodingRequest[1] = 0x4B;
        break;
    }

    return lineEncodingRequest;
}

There is a switch case stracture for setting the baud rate as 9600, 14400 or 19200. But I want it to be 115200 Can anyone tell me how I can do that?

Answer

epichorns picture epichorns · Jul 14, 2014

Here is a modified function that generalizes your function above for other baud rates:

private byte[] getLineEncoding(int baudRate) {
    final byte[] lineEncodingRequest = { (byte) 0x80, 0x25, 0x00, 0x00, 0x00, 0x00, 0x08 };
    //Get the least significant byte of baudRate, 
    //and put it in first byte of the array being sent
    lineEncodingRequest[0] = (byte)(baudRate & 0xFF);

    //Get the 2nd byte of baudRate,
    //and put it in second byte of the array being sent
    lineEncodingRequest[1] = (byte)((baudRate >> 8) & 0xFF);

    //ibid, for 3rd byte (my guess, because you need at least 3 bytes
    //to encode your 115200+ settings)
    lineEncodingRequest[2] = (byte)((baudRate >> 16) & 0xFF);

    return lineEncodingRequest;

}