0

我目前正在尝试使用 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 写一个句点,它将返回这些值。这是我的蓝牙代码,它与蓝牙聊天示例中的代码非常相似:

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 的值

而不是全部在一行中。当我通过蓝牙(蓝牙加密狗)将 arduino 连接到计算机时,数据在一行中返回。如何确保数据在一行中返回。

4

2 回答 2

1

出色地。我遇到过同样的问题。为了解决它,我使用mDinput = new DataInputStream(mmInStream);, then mDinput.readFully(dateBuffer, 0, sizeYouWant);。然后,readFully仅当缓冲区已满时才会返回给您

希望这可以帮助

于 2013-08-23T09:47:35.967 回答
1

我可以尝试将您的数据连接到“缓冲区”中并检查此缓冲区是否有新的行/回车符。一旦找到,您将数据分配给您的真实变量,清除缓冲区并重新开始。这应该够了吧。

希望能帮助到你!:)

于 2013-08-22T07:31:43.743 回答