2017-02-22 45 views
1

我遇到了一些与arduino有关的问题。在课堂上,我们正在学习arduino/java通信。因此,我们被要求解释从arduino发送的字节,并在eclipse的控制台中写出它,因为消息的“关键”告诉我们写入它的任何类型。尝试使用eclipse从Arduino中读取时获取不完整的消息?

截至目前,我只是测试输入流,但我似乎无法得到一个完整的消息。这是我在做什么:

public void run() throws SerialPortException { 
    while (true) { 
     if (port.available()) {  //code written in another class, referenced below 
      byte byteArray[] = port.readByte(); //also code written in another class, referenced below 
      char magicNum = (char) byteArray[0]; 
      String outputString = null; 
      for (int i = 0; i < byteArray.length; ++i) { 
       char nextChar = (char) byteArray[i]; 
       outputString += Character.toString(nextChar); 
      } 
      System.out.println(outputString); 
     } 

    } 
} 
下面

是来自在上面的代码中使用的其它类的代码

public boolean available() throws SerialPortException { 
    if (port.getInputBufferBytesCount() == 0) { 
     return false; 
    } 
    return true; 
} 

public byte[] readByte() throws SerialPortException { 
    boolean debug= true; 
    byte bytesRead[] = port.readBytes(); 
    if (debug) { 
     System.out.println("[0x" + String.format("%02x", bytesRead[0]) + "]"); 
    } 
    return bytesRead; 
} 
+0

我忘了提及,我从arduino接口输入的输入流是“这是一个测试”,我得到的输出如“nullthis是a”和“nulla test”或者只是“null” – Harrison

回答

0

这是不可能知道数据将是可用的,也不是是否输入数据将一次全部可用,而不是几个块。

这是一个快速和肮脏的修复

public void run() throws SerialPortException { 
    String outputString = ""; 
    while (true) { 
     if (port.available()) { 
      byte byteArray[] = port.readByte(); 

      for (int i = 0; i < byteArray.length; ++i) { 
       char nextChar = (char) byteArray[i]; 

       if (nextChar == '\n') { 
        System.out.println(outputString); 
        outputString = ""; 
       } 

       outputString += Character.toString(nextChar); 
      } 
     } 
    } 
} 

outputString声明被移出,并且被分配""所以要获得标准输出摆脱这种丑陋null

每次\n串行输入数据遇到的outputString内容打印在标准输出第一和之后清零。