Command Format to send to OBD (Android)

2.4k Views Asked by At

Having trouble figuring out how to format the commands I send to my OBD device. First off Torque is working fine so I know its my code that's the problem not the device.

Here's how I'm sending my commands:

public void run() {

            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    byte[] command = new byte[5];
                    command[0] = rawToByte(268);
                    //command[1] = rawToByte(269);

                    Log.i("gas", "Command: "+Byte.toString(command[0]));
                    write(command);
    /////////////////////////////////////////    problem with below line               
                    bytes = mmInStream.read(buffer);
                    Log.i("gas", "Response: "+Integer.toString(bytes));
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    break;
                }
            }
        }

This is based off some research I was doing, if anyone can suggest an easy way, that would be appreciated. 268 is the decimal equivalent of "010C" which is the code for engine rpm according to the elm327 sheet.

My write() method:

public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
                mmOutStream.flush();

            } catch (IOException e) { }
        }

And my rawToByte() method:

public byte rawToByte(int b) {
            return (byte) (0xff & b);
        }

The response log cat reads "5" every time and same if I use 269 for speed. This might be an error code that im sending the commands wrong. The write() method on the socket mmOutStream only takes bytes and the rawToByte method I got from some question on here (which doesnt answer this question) only takes integers so i cant feed it "010C", but this shouldn't make a difference.

My application needs to constantly get speed and rpm of a vehicle.

Can anybody specify (simply) how to properly send commands to an OBDII Elm327 device?

1

There are 1 best solutions below

9
On BEST ANSWER

I'm not sure if you are still in need of an answer, but here is how I would try to do it:

String message = "010D\r";
mmOutStream.write(message.getBytes());
byte[] buffer = new byte[1024];
mmInStream.read(buffer);

Then convert the buffer back to a string. You may need to add a couple steps to remove the empty bytes from your array to get the results you are looking for. Hope that helps!