2015-10-19 44 views
0

我已經編寫了Android代碼連接到藍牙HC-05,向HC-05發送命令並接收與發送的命令相關的不同數據。 Android應用程序連接藍牙和發送第一條命令時,它會收到我想要的確切數據,但下一條命令會收到符號「 」以及相關數據。Android藍牙串行通信讀取符號「 」

我已經測試了與其他藍牙終端在Android上的硬件電路,它的工作原理是完美的。

以下是我的串行通信代碼:

void beginListenForData() { 
     final Handler handler = new Handler(); 
     final byte delimiter = 10; 
     stopWorker = false; 
     readBufferPosition = 0; 
     readBuffer = new byte[1024]; 
     workerThread = new Thread(new Runnable() { 
      public void run() { 
       while (!Thread.currentThread().isInterrupted() && !stopWorker) { 
        try { 
         int bytesAvailable = mmInputStream.available(); 

         if (bytesAvailable > 0) { 
          byte[] packetBytes = new byte[bytesAvailable]; 
          mmInputStream.read(packetBytes); 

          for (int i = 0; i < bytesAvailable; i++) { 
           byte b = packetBytes[i]; 
           if (b == delimiter) { 
            byte[] encodedBytes = new  byte[readBufferPosition]; 
            System.arraycopy(readBuffer, 0, 
              encodedBytes, 0, 
              encodedBytes.length); 
            final String data = new String(
              encodedBytes,"US-ASCII"); 
            readBufferPosition = 0; 

            handler.post(new Runnable() { 
             public void run() { 
              sampleView.setText(data); 
              str = sampleView.getText() 
                .toString(); 
              Log.i("Data", data);           
} 

            }); 
           } else { 
            readBuffer[readBufferPosition++] = b; 
           } 
          } 
         } 

        } catch (IOException ex) { 
         stopWorker = true; 
        } 
       } 

      } 


     }); 

     workerThread.start(); 
     try { 


      String command1=command.getText().toString(); 
      mmOutputStream.write(command1.getBytes()); 



     } catch (IOException e) { 

      e.printStackTrace(); 
     } 
    } 

請幫助!

回答

0

有時候會出現這種亂碼,你應該注意你的字符格式。你可以將你的命令轉換爲「UTF-8」。

另一種情況可能是:您從錯誤的開始或結束位置讀取數據。

+0

對不起延遲迴復...我曾嘗試「UTF-8」,但情況沒有改變。 – user2718012

+0

這個符號的HEX表示是什麼?它不一定是「 」,但可能是「無法識別」字符的表示。 我想問題是你的分隔符檢測。如果HC-05發送的UTF字符的低位字節爲0x10,則可能會被您的代碼誤解。 – Andrew

+0

如果問題是分隔符檢測,那麼它總是會發送這個符號。但在第一個命令的情況下,它發送正確的數據和第二個命令,它的代碼讀取符號和數據。你認爲我應該在上面的代碼中做出什麼改變? – user2718012