【问题标题】:Arduino can read bytes from console, but not from javaArduino 可以从控制台读取字节,但不能从 java
【发布时间】:2019-04-28 16:58:01
【问题描述】:

我想在 Arduino Uno 上从 Java 程序接收多个字节。 arduino 收到数据后会立即处理,因此我不需要存储它,我使用串行 RX 缓冲区作为临时存储,直到我真正读取字节。完全实现后,每次将发送大约 150 个字节,但我已经修改了缓冲区大小以解决这个问题。我使用 jSerialComm 作为我的 java 串行库

我在下面放了一些 arduino 和 java 代码。当我从 IDE 的串行监视器发送字节时,arduino 代码可以完美运行,按预期点亮 LED。但是,一旦我尝试使用 java 代码发送字节,RX 板载 LED 就会闪烁,但黄色 LED 永远不会亮起,并且 ExecuteMove() 不会触发。我尝试在尝试关闭端口之前放置一个 Thread.sleep() ,但这无济于事。

阿杜诺

int GREEN = 4;
int BLUE = 3;
int YELLOW = 2;

void setup() {
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(YELLOW, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  byte rb = Serial.read();
  if(rb != 255){ //Documentation says it sould be -1, but I'v tested it and 
                   it's 255
    digitalWrite(YELLOW, HIGH);
    ExecuteMove(rb);
    delay(500);
    digitalWrite(YELLOW, LOW);
  }
}

void ExecuteMove(byte _move){ 
  Lights up the green LED if _move == 65, blue if 66 (Works perfectly)  
}

Java

public static void main(String[] args) throws IOException, 
                                              InterruptedException{

    SerialPort sp = SerialPort.getCommPort("COM3");
    sp.setComPortParameters(9600, 8, 1, 0);
    sp.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0);

    if(sp.openPort()) {
        System.out.println("Port is open");
    }else {
        System.out.println("Port failed to open");
        return;
    }

    byte[] message = {65, 66, 65};
    for(int i = 0; i < message.length; i++) {
        sp.getOutputStream().write(message[i]); //Sends the message
        sp.getOutputStream().flush();
    }

    if(sp.closePort()) { 
        System.out.println("Port is closed"); 
    }else { 
        System.out.println("Failed to close port"); 
        return; 
    } 
}  

正如我已经说过的,arduino 代码单独与显示器完美配合,但是当我使用 java 代码发送字节时,只有 RX LED 亮起,但“我的”LED 都不亮

【问题讨论】:

  • 尽量不要关闭Java程序,在main返回前加一个Thread.sleep(2000),因为它关闭了串口通讯。监视器不这样做。
  • 关于:if(rb != 255){ //Documentation says it sould be -1, but I'v tested it and it's 255 - 返回值为int,而不是byte
  • @Aubin 我试过了,但它也不起作用(用额外的信息编辑了我的帖子)

标签: java arduino serial-port


【解决方案1】:

对于任何偶然发现这篇文章并且似乎有类似问题的人,这是因为 Windows 在打开端口时向 arduino 发送了一个重置​​信号。因为它会立即发送数据,所以 Arduino 在重置时会将其从缓冲区中删除,并且永远无法读取它。有两种主要的纠正方法,首先在打开端口和发送数据之间添加Thread.sleep(5000);。您还可以在 RESET 和 GND 引脚之间添加一个 47μF 的电容。

来源:https://arduino.stackexchange.com/questions/22267/java-jssc-arduino-windows https://forum.arduino.cc/index.php?topic=96422.0

希望这可以帮助某人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2013-10-08
    相关资源
    最近更新 更多