从Java发送字符串到Arduino(简单示例)

tak*_*per 10 java serial-port arduino

它解决了.我Thread.sleep(4000);在java代码中打开端口后现在可以正常工作了.问题是每次打开端口时都会重置arduino.当我发送数据时,arduino还没准备好听.

我是arduino和Java的新手,但我制作的程序非常简单,我不明白为什么不工作.

我发送一个字符串到与arduino(COM5)对应的串口:

import java.io.*;
import java.util.*;
import gnu.io.*;

public class SimpleWrite {

static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "color FF00FFEND";
static SerialPort serialPort;
static OutputStream outputStream;

public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();


    while (portList.hasMoreElements()) {

        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

             if (portId.getName().equals("COM5")) {

                try {
                    serialPort = (SerialPort)
                    portId.open("SimpleWriteApp", 2000);

                    outputStream = serialPort.getOutputStream();

                    serialPort.setSerialPortParams(9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                    outputStream.write(messageString.getBytes());
                    System.out.println(messageString);

                    outputStream.close();
                    serialPort.close();
                } 
                catch (IOException e) {System.out.println("err3");}
                catch (PortInUseException e) {System.out.println("err");}
                catch (IOException e) {System.out.println("err1");}
                catch (UnsupportedCommOperationException e) {System.out.println("err2");}
            }
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

和arduino中的代码来获取该字符串:

char inputBuffer[10];   

void setup() {                
  Serial.begin(9600);  
}

void loop() {
    while (true) 
    {
      if (Serial.available() > 0) {
          Serial.readBytes(inputBuffer, Serial.available());
          delay(5000);
          Serial.print("I got this ->");
          Serial.print(inputBuffer);
          Serial.println("<-");
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

while(true)用于测试目的.我什么都没打印,我不知道问题出在哪里.我在这里看到了关于arduino和java的所有帖子,我没有发现任何有用的东西.感谢您的帮助和对不起,如果这是一个愚蠢的问题,我是一个新手

我正在使用RXTXcomm.jar.版本:RXTX-2.2-20081207

tak*_*per 4

解决了。我Thread.sleep(4000)在java代码中打开端口后添加了一个,现在它可以工作了。问题是每次打开端口时 Arduino 都会重置,所以我在 Arduino 没有准备好监听时发送数据。

char inputBuffer[10];   

void setup()
{                
    Serial.begin(9600);  
}

void loop()
{
     while (true) 
     {
          if (Serial.available() > 0)
          {
              Serial.readBytes(inputBuffer, 10);
              delay(5000);
              Serial.print("I got this ->");
              Serial.print(inputBuffer);
              Serial.println("<-");
          }
     }
}
Run Code Online (Sandbox Code Playgroud)