2017-01-31 24 views
0

我正在一個項目上,我得到了一個Arduino sensurata它通過串行打印到我的筆記本電腦。當我使用Arduino IDE時,串行監視器可以正常工作。 (完整的信息如下所示:1-35 251 58 152)。 -之後的字符是UID,因此它們應該始終與我僅使用一個設備進行測試的相同。試圖通過串行讀取數據與掃描儀不看完整行

當我嘗試通過Java閱讀這個消息時,我得到了不同的消息(或者至少不完整的消息)。

public void setupUSB() { 
    SerialPort ports[] = SerialPort.getCommPorts(); 
    for (SerialPort port : ports) { 
     if (port.getSystemPortName().equals("COM6")) myPort = port; // using LoRa over USB 
    } 
    myPort.setBaudRate(38400); 
    myPort.openPort(); 
    myPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0); 
} 

上面的方法啓動我正在使用的USB端口。 經過一些檢查後,我嘗試讀取端口如下(刪除嘗試捕獲和其他不重要的代碼到這個問題)。

Scanner data = new Scanner(myPort.getInputStream()).useDelimiter("\n"); 
if (data.hasNext()) { 
    String line = data.next(); 
    System.out.println("readUSB: " + line); 
} 

我也曾嘗試以下操作:這我是從System.out.println("readUSB: " + line);越來越

Scanner data = new Scanner(myPort.getInputStream()); 
if (data.hasNextLine()) { 
    String line = data.nextLine(); 
    System.out.println("readUSB: " + line); 
} 

結果如下:

readUSB: � 
readUSB: 152 
readUSB: 9-35 251 58 152 
readUSB: 152 
readUSB: 1-35 251 58 152 
readUSB: 5 251 58�152 
readUSB: 251 58 152 
readUSB: 
readUSB: 58 152 

正如你看到的(有一些噪音在消息中),這些消息大部分都不完整。

有誰能告訴我是什麼原因造成的以及如何修復它?

[編輯]

正如我使用LORA將數據從一個傳感器傳送到另一個的Arduino,我收集數據作爲字符。 Arduino和我的USB端口在38400上使用相同的波特率。我覺得錯誤可能出現在下面的代碼中,因爲當我連接傳感器USB(而不是通過LoRa發送)時,這些值實際上是正確的。

if (packetFound) { 
    // Print the packet over Serial per character 
    Serial.println(); 
    for (int i=0; i<19; i++) { //20 and 21 are squares 
    Serial.print(char(RxData[i])); 
    RxData[i] = 0x00; // Clear buffer [0x20 -> space] 
    } 
} 
+0

很微不足道的問題,但我應該問一下,對不起。 你確定波特率匹配嗎? P.S.請添加arduino代碼 –

+0

您使用的是匹配的字符集嗎? –

+0

爲什麼不使用'InputStream'從串口讀取數據?兩個有用的資源與'InputStream'相關:1. http://stackoverflow.com/questions/336714/reading-serial-port-in-java 2. http://www.java-samples.com/showtutorial.php? tutorialid = 11 –

回答

0

我似乎無法擺脫這個問題,但我注意到以下幾點。

如果我一個字符串添加到郵件中的Arduino前我得到的結果是這樣的:

  • readUSB:LLO世界:9-35 251 58 152(很顯然,這應該說Hello World)。

我目前的解決方案,以問題是增加了一套10個#字符我在Arduino的字符串的開始,後來篩選出來的字符串。

while (line.charAt(0) == '#') { // Remove all the # chars in front of the real string 
    line = line.substring(1, line.length()); 
} 

正如評論所說:更好的方式來寫這個代碼:

int i = 0; 
while (line.charAt(i) == '#') { 
    i++; 
} 
line = line.substring(i); 

我接受這個答案,因爲它適用於我的問題。但是如果有人對此問題有真正的解決方案,請將其發佈,我會接受它。

+1

這不是處理字符串的有效方法,因爲'substring()'會創建一個新的'String'對象N次,並且舊的字符串將被釋放到垃圾收集器。最好找到字符串中第一個非#的索引('while(line.charAt(i)=='#')++ i;'),然後取一個子字符串。這不會解決您的問題,但只是對字符串處理最佳實踐的一般性評論。 –