java - Java RXTX 与 Arduino 串口通信

标签 java serial-port arduino rxtx

我正在尝试使用串行端口在我的 PC(使用 Netbeans 和 RXTX 的 Windows 7)与 Arduino Pro 之间进行通信。 Arduino 实际上是使用 FTDI 电缆连接到 PC 的。

代码是基于Java的SimpleRead.Java找到的here.

目前,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");
    }
}

最佳答案

串行数据只是一种数据流。根据您读取它的时间和正在发生的缓冲,当您读取它时可能只有部分数据可用。

由于您使用的是面向行的数据,因此您要做的是缓冲数据,直到看到行终止符,然后才处理数据。

关于java - Java RXTX 与 Arduino 串口通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2009173/

相关文章:

c# - 尝试进行串行端口通信,返回 0x102 作为返回码

arduino - Serial.begin(speed, config) 没有为 Leonardo Board 编译

java - Android Arduino 蓝牙通信启动时崩溃

java - FileInputStream 是否有内部缓冲区

java - 添加此方法后,我得到一个空指针

Java 正则表达式 View 状态

java - 在Java中用下划线+小写字母替换大写字母?

c - 检测 COM 端口是否已关闭

linux - arduino Yun 和 nodejs 上的 Linino (openWRT) - Nodejs 串行模块不工作

c++ - Arduino int 到字符串的转换