Android : Can't send data to Arduino Due from Android via Bluetooth

on Tuesday, July 29, 2014


I have written an Android app that's supposed to send data to Arduino Due via Bluetooth Module (ZS-040). Bluetooth connection is fine. However, Arduino doesn't seem to receive any data from Android. When I send data to Arduino through the Serial Monitor though, it works. I've looked into many stackoverflow questions and other guides online but can't seem to figure out what's wrong.


Here's some code:


Thread for connecting the two devices:



private class ConnectThread extends Thread {
private BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//uuid for Arduino bluetooth module

public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;

try {
tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { };
socket = tmp;
}

public void run() {
mBluetoothAdapter.cancelDiscovery();
runOnUiThread(new Runnable() {
@Override
public void run() {
findBtn.setText("Search for devices");
}
});

try {
socket.connect();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException connectionException) {
try {
socket.close();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "An error has occured. Please try again.",
Toast.LENGTH_SHORT).show();
}
});
} catch (IOException closeException) { }
return;
}
}
}


Code for sending data to Arduino; function is called when a button is pressed.



public void sendData(View view) {
// write to OutputStream
OutputStream mmOutputStream = null;
try {
mmOutputStream = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}
// String message = "0";
// byte[] msgBuffer = message.getBytes();

try {
mmOutputStream.write('0');
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}
}


Arduino code (directly copied from here):



char incomingByte; // incoming data
int LED = 12; // LED pin

void setup() {
Serial.begin(9600); // initialization
pinMode(LED, OUTPUT);
Serial.println("Press 1 to LED ON or 0 to LED OFF...");
}

void loop() {
if (Serial.available() > 0) { // if the data came
incomingByte = Serial.read(); // read byte
if(incomingByte == '0') {
digitalWrite(LED, LOW); // if 1, switch LED Off
Serial.println("LED OFF. Press 1 to LED ON!"); // print message
}
if(incomingByte == '1') {
digitalWrite(LED, HIGH); // if 0, switch LED on
Serial.println("LED ON. Press 0 to LED OFF!");
}
}
}


EDIT: Because it's a DUE with which I'm working, I can't use SoftwareSerial library. :(


0 comments:

Post a Comment