Java RXTX 与 Arduino 之间的串行通信

发布于 2024-08-17 02:08:30 字数 1668 浏览 7 评论 0原文

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

该代码基于此处找到的 Java SimpleRead.Java。

目前,Arduino 在启动时仅打印出一个字符串。我的Java程序应该打印已读取的字节数,然后打印出内容。 Java 程序可以正常工作...

如果字符串很长(>10 个字节左右),则输出将被破坏。

因此,如果在 Arduino 上我打印

Serial.println("123456789123456789"); //20 bytes including '\r' and '\n'

The output of my Java program 可能看起来像这样:

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

I'm trying to communicate between my PC (Windows 7 using Netbeans and RXTX) with an Arduino Pro, using the serial port. The Arduino is actually connected to the PC using an FTDI cable.

The code is based on the Java SimpleRead.Java found here.

Currently the Arduino simply prints out a string when it starts up. My Java program should print the number of bytes that have been read and then print out the contents. The Java program works, sort of...

If the string is long (>10 bytes or so) the output will get broken up.

So if on the Arduino I print

Serial.println("123456789123456789"); //20 bytes including '\r' and '\n'

The output of my Java program may look something like:

Number of Bytes: 15   
1234567891234  
Number of Bytes: 5  
56789

or

Number of Bytes: 12   
1234567891  
Number of Bytes: 8  
23456789

I'm thinking it's a timing problem, because when I manually go through the code using the debugger, the result string is always what it should be: one 20 byte string.

I've been messing with various things but I haven't been able to fix the problem.

Here is the part of the code that is giving me problems:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酸甜透明夹心 2024-08-24 02:08:30

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

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

Serial data is just a stream of data. Depending on when you read it and the buffering that is happening, only part of the data may be available when you read it.

Since you are using line oriented data, what you will want to do is buffer the data until you see the line terminator and only then process the data.

羞稚 2024-08-24 02:08:30

我没有使用过 Java RXTX,但我使用过 Arduino 和Processing,并且从 Arduino 读取/写入值非常容易。
这是一个带有处理的读取示例(文件>示例>库>串行> SimpleRead)

/**
 * Simple Read
 * 
 * Read data from the serial port and change the color of a rectangle
 * when a switch connected to a Wiring or Arduino board is pressed and released.
 * This example works with the Wiring / Arduino program that follows below.
 */


import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port

void setup() 
{
  size(200, 200);
  // I know that the first port in the serial list on my mac
  // is always my  FTDI adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  if ( myPort.available() > 0) {  // If data is available,
    val = myPort.read();         // read it and store it in val
  }
  background(255);             // Set background to white
  if (val == 0) {              // If the serial value is 0,
    fill(0);                   // set fill to black
  } 
  else {                       // If the serial value is not 0,
    fill(204);                 // set fill to light gray
  }
  rect(50, 50, 100, 100);
}



/*

// Wiring / Arduino Code
// Code for sensing a switch status and writing the value to the serial port.

int switchPin = 4;                       // Switch connected to pin 4

void setup() {
  pinMode(switchPin, INPUT);             // Set pin 0 as an input
  Serial.begin(9600);                    // Start serial communication at 9600 bps
}

void loop() {
  if (digitalRead(switchPin) == HIGH) {  // If switch is ON,
    Serial.print(1, BYTE);               // send 1 to Processing
  } else {                               // If the switch is not ON,
    Serial.print(0, BYTE);               // send 0 to Processing
  }
  delay(100);                            // Wait 100 milliseconds
}

*/

据我记得,实例化串行时在Arduino中设置的波特率非常重要。例如,如果您使用 9600 发送,则应该使用相同的号码来收听。

此外,以 BYTE 形式发送您的信息也非常重要,否则您将遇到 \r 或 \n 之类的内容。

较短的版本,尝试一下:

Serial.println(123456789123456789,BYTE);

越简单越好。

I haven't used Java RXTX, but I've played with Arduino and Processing and it's pretty easy to read/write values from Arduino.
Here is a read sample that comes with Processing(File > Examples > Libraries > Serial > SimpleRead)

/**
 * Simple Read
 * 
 * Read data from the serial port and change the color of a rectangle
 * when a switch connected to a Wiring or Arduino board is pressed and released.
 * This example works with the Wiring / Arduino program that follows below.
 */


import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port

void setup() 
{
  size(200, 200);
  // I know that the first port in the serial list on my mac
  // is always my  FTDI adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  if ( myPort.available() > 0) {  // If data is available,
    val = myPort.read();         // read it and store it in val
  }
  background(255);             // Set background to white
  if (val == 0) {              // If the serial value is 0,
    fill(0);                   // set fill to black
  } 
  else {                       // If the serial value is not 0,
    fill(204);                 // set fill to light gray
  }
  rect(50, 50, 100, 100);
}



/*

// Wiring / Arduino Code
// Code for sensing a switch status and writing the value to the serial port.

int switchPin = 4;                       // Switch connected to pin 4

void setup() {
  pinMode(switchPin, INPUT);             // Set pin 0 as an input
  Serial.begin(9600);                    // Start serial communication at 9600 bps
}

void loop() {
  if (digitalRead(switchPin) == HIGH) {  // If switch is ON,
    Serial.print(1, BYTE);               // send 1 to Processing
  } else {                               // If the switch is not ON,
    Serial.print(0, BYTE);               // send 0 to Processing
  }
  delay(100);                            // Wait 100 milliseconds
}

*/

As far as I remember, the baud thingy you setup in Arduino when you instantiate Serial is pretty important. If you use 9600 to send for example, you should use the same number to listen.

Also it's pretty important to send your information as BYTE, otherwise you'll have stuff like \r or \n in the way.

Shorter version, try:

Serial.println(123456789123456789,BYTE);

The simpler the better.

帝王念 2024-08-24 02:08:30

我认为你需要使用事件驱动的设计模式来解决这个问题。我强烈建议您访问:http://www.whatisarduino。 org/bin/Tutorials/Java+Serial+API+and+Arduino

I think you need to use event driven design patterns to solve this problem. I highly recommend you to visit: http://www.whatisarduino.org/bin/Tutorials/Java+Serial+API+and+Arduino

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文