我正在尝试使用串口通信在我的电脑(Windows 7,使用Netbeans和RXTX)与一个Arduino Pro之间进行通信。实际上,Arduino是使用FTDI电缆连接到计算机的。
这段代码基于Java SimpleRead.Java,可以在这里找到。
目前,当Arduino启动时,它只会打印出一个字符串。我的Java程序应该打印出已经读取的字节数,然后打印出内容。这个Java程序正在工作,但有些问题...
如果字符串很长(大于10个字节左右),输出将会被分割成几部分。
因此,如果我在Arduino上打印:
这段代码基于Java SimpleRead.Java,可以在这里找到。
目前,当Arduino启动时,它只会打印出一个字符串。我的Java程序应该打印出已经读取的字节数,然后打印出内容。这个Java程序正在工作,但有些问题...
如果字符串很长(大于10个字节左右),输出将会被分割成几部分。
因此,如果我在Arduino上打印:
Serial.println("123456789123456789"); //20 bytes including '\r' and '\n'
我的Java程序的输出可能会像这样:
Number of Bytes: 15
1234567891234
Number of Bytes: 5
56789
或者Number of Bytes: 12
1234567891
Number of Bytes: 8
23456789
我认为这是一个时间问题,因为当我使用调试器手动浏览代码时,结果字符串总是正确的:一个20字节的字符串。
我已经尝试了一些不同的方法,但还是没有解决问题。
以下是导致问题的代码部分:
static int baudrate = 9600,
dataBits = SerialPort.DATABITS_8,
stopBits = SerialPort.STOPBITS_1,
parity = SerialPort.PARITY_NONE;
byte[] readBuffer = new byte[128];
...
...
public void serialEvent(SerialPortEvent event)
{
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
if (input.available() > 0) {
//Read the InputStream and return the number of bytes read
numBytes = input.read(readBuffer);
String result = new String(readBuffer,0,numBytes);
System.out.println("Number of Bytes: " + numBytes);
System.out.println(result);
}
} catch (IOException e) {
System.out.println("Data Available Exception");
}
}