我一直在尝试与我的 Arduino Uno 使用串行通信,并使用了库 jSSC-2.6.0。我正在使用SeriaPortEvent侦听器从串行端口(Arduino)接收字节并将它们存储在链接列表中。
public synchronized void serialEvent(SerialPortEvent serialPortEvent) {
if (serialPortEvent.isRXCHAR()) { // if we receive data
if (serialPortEvent.getEventValue() > 0) { // if there is some existent data
try {
byte[] bytes = this.serialPort.readBytes(); // reading the bytes received on serial port
if (bytes != null) {
for (byte b : bytes) {
this.serialInput.add(b); // adding the bytes to the linked list
// *** DEBUGGING *** //
System.out.print(String.format("%X ", b));
}
}
} catch (SerialPortException e) {
System.out.println(e);
e.printStackTrace();
}
}
}
}
现在,如果我在循环中发送单个数据并且不等待任何响应,serialEvent 通常会将接收到的字节打印到控制台。但是,如果我尝试等到链表中有一些数据,程序只会继续循环,并且 SerialEvent 永远不会向 LinkedList 添加字节,它甚至不会注册任何接收到的字节。
这是可行的,并且正确的字节由 Arduino 发送,并由 SerialEvent 接收并打印到控制台:
while(true) {
t.write((byte) 0x41);
}
但是这个方法只是停留在 this.available() 上,它返回 LinkedList 的大小,因为实际上没有从 Arduino 接收到任何数据或由 serialEvent 接收:
public boolean testComm() throws SerialPortException {
if (!this.serialPort.isOpened()) // if port is not open return false
return false;
this.write(SerialCOM.TEST); // SerialCOM.TEST = 0x41
while (this.available() < 1)
; // we wait for a response
if (this.read() == SerialCOM.SUCCESS)
return true;
return false;
}
我已经调试过程序,有时也调试过,程序确实可以工作,但并非总是如此。此外,只有当我尝试检查链表中是否有一些字节时,程序才会卡住,即 while(available() < 1)。否则,如果我不检查,我最终会从 Arduino 收到正确的字节响应