現在、Bluesmirf モジュールを使用して Arduino から Android にデータを取得しようとしています。
これがArduino用の私のコードです。
void setup() {
Serial.begin(115200);
}
void loop() {
if(Serial.available()){
char val = Serial.read();
if(val == '.'){
Serial.println("t1|x1|x2|x3|x4");
}
}
}
ご覧のとおり、長い文字列を書き込んでいるだけです。最終的に、文字列には値が含まれます。arduino にピリオドを書き込むと、それらの値が返されます。これが私の Bluetooth コードです。これは、Bluetooth チャット サンプルのものと非常によく似ています。
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;
}
}
}
私が言及したいいくつかのこと。System.gc() があるのは、そこに配置しないと、誤ったデータを取得することがあるためです。データが失われることもあれば、繰り返されることもあります。
私が抱えている問題は、出力が複数行で返されることです。だから私のログでは、次のようなものを取得します
出力 t1|x1|x の値
出力 2|x3|x4 の値
代わりに、すべてを 1 行にまとめます。Bluetooth(Bluetoothドングル)を介してarduinoをコンピューターに接続すると、データが1行で返されます。データが 1 行で返されるようにするにはどうすればよいですか。