Friday, March 9, 2012

Android Arduino communication

I've managed to get my Android phone (Galaxy Nexus) and the arduino fio communicating over bluetooth.  There were a couple of things to watch out for however,

  1. When programming the Bluetooh Bee you have to use a baud rate of 38400.  When it's in normal mode it will use whatever baud rate you have set via AT+BAUD.
  2. Some android devices can't see Bluetooth devices that have a device class of 0 (which is the bluetooth bee default).  I'd suggest setting the device class, in my case the command looks like: "AT+CLASS=0x8C080C\r\n".  You can generate a device class numbers from this CoD Generator
  3. For some reason my phone would not create a valid socket to the device using the standard createRfcommSocket.  After searching around a bit I found this tread, changing this code made it work.
  4. Silly note, but:  you have to pair your phone with the device.  It is necessary to go to the bluetooth menu in the settings on the Android device, select the Arduino device (in my case called "DefilerBot"), and enter the pin.  The pin by default is "1234" but can be changed with the "AT+PSWD=1122" command.
// Change
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
// To
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);

The base code for the Bluetooth connection and messaging came from the Android Bluetooth chat example.

My Bluetooth Bee Arduino config program now looks like this.

void setup(){
  Serial.begin(38400);
  Serial.write("AT+UART=57600,0,0\r\n");
  checkResponse();
  Serial.write("AT+CLASS=0x8C080C\r\n");
  checkResponse();
  Serial.write("AT+ROLE=0\r\n");
  checkResponse();
  Serial.write("AT+NAME=DefilerBot\r\n");
  checkResponse();
}

void checkResponse(){
  delay(500);
  String inputString = "";
  if(!Serial.available())
  {
     digitalWrite(13, HIGH);
     delay(1000);
     digitalWrite(13, LOW);
  }
  while (Serial.available()){
    char inChar = (char)Serial.read(); 
    inputString += inChar;
    if (inChar == '\n'){
      if(inputString == "OK\r\n"){
        digitalWrite(13, HIGH);
        delay(200);
        digitalWrite(13, LOW);
        delay(200);
        digitalWrite(13, HIGH);
        delay(200);
        digitalWrite(13, LOW);
        delay(200);
        digitalWrite(13, HIGH);
        delay(200);
        digitalWrite(13, LOW);
      }
      else
      {
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
      }
    } 
  }
  delay(1000);
}

void loop(){
  digitalWrite(13, HIGH);
  delay(500);
  digitalWrite(13, LOW);
  delay(500);
}

1 comment: