Send/Recieve Hex Over Bluetooth SPP from Android

If you have used any of my earlier blog posts for sending data to a bluetooth module from an Android device you may have noticed you can only send ASCII characters. This is fine for most activities but what if you need to send carriage return or line feed, which are 0xD and 0xA respectively.

Simply add a new method to send an int, which represents the hexadecimal you wish to send.

public void writeHex(int i) { 
  try { 
    mmOutStream.write(i); 
  }catch (IOException e) { 
    finish(); 
    Toast.makeText(getBaseContext(), "DEVICE UNAVAILABLE", Toast.LENGTH\_SHORT).show(); 
  } 
}

Do what you want in the catch statement, I have lazily told my activity to finish if an exception is raised.

To use this new method just call it like I have below. In this example I am using it to send the line feed command (0xA).

mConnectedThread.writeHex(0xA); 

mConnectedThread is just the name of the thread I am using to handle my bluetooth methods. Notice you have to write 0x before the hexadecimal value, simply writing A would not work.

 

Now say you have received a load of ASCII via bluetooth but for some reason you want to display it as hexadecimals. I found the best way to do this is to add a string conversion method.

private String convertStringToHex(String string) { 
  newString = new StringBuilder(); 
  for (int i=0; i<string.length(); i++) {
    newString.append(String.format("%x ", (byte)(string.charAt(i)))); 
  } 
  return newString.toString(); 
} 

Simply pass in your string of ASCII characters and the returned string will be in hex. I wanted spaces between my values so I put a space after %x but if you prefer it without just remove it.