I'm currently trying to get data from an Arduino to Android using the Bluesmirf module.
Here is my code for the Arduino.
void setup() {
Serial.begin(115200);
}
void loop() {
if(Serial.available()){
char val = Serial.read();
if(val == '.'){
Serial.println("t1|x1|x2|x3|x4");
}
}
}
As you can see, I'm just having it write a long string. Eventually, the string will contain values. If i write a period to the arduino, it will return those values. Here is my Bluetooth Code, its very similar to the one in the Bluetooth Chat Sample:
private class ConnectedThread extends Thread{
private BluetoothSocket mmSocket;
private InputStream mmInStream;
private OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
// TODO Auto-generated constructor stub
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (Exception e) {
// TODO: handle exception
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024];
int bytes;
while(true){
try {
// Garbage collector necessary to prevent data loss
System.gc();
bytes = mmInStream.read(buffer);
Log.d("Value of Output", new String(buffer, 0, bytes))
} catch (IOException e) {
e.printStackTrace();
connectionLost();
}
}
}
public void write(byte[] buffer){
try{
mmOutStream.write(buffer);
} catch(IOException e){
Log.d("Write", "failed");
}
}
public void cancel(){
if (mmInStream != null) {
try{mmInStream.close();}catch(Exception e){}
mmInStream = null;
}
if (mmOutStream != null) {
try{mmOutStream.close();} catch(Exception e){}
mmOutStream = null;
}
if (mmSocket != null) {
try{mmSocket.close();}catch(Exception e){}
mmSocket = null;
}
}
}
A few things I want to mention. The System.gc() is there because if I don't put it there, I sometimes get faulty data. Sometimes the data is loss, sometimes it's repeated.
The problem that I'm having is that the output comes back in more than one line. So in my log I'll get something like
The value of Output t1|x1|x
the value of Output 2|x3|x4
Instead of it all in one line. When I connect the arduino to the computer via Bluetooth(bluetooth dongle), the data comes back in one line. How can I ensure that the data comes back in one line.