我一直在尝试使用与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添加字节,它甚至都不会记录任何正在接收的字节 .
这有效,并且由SerialEvent收到的Arduino发送正确的字节并打印到控制台:
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;
}
我调试了程序,有时调试,程序确实有效,但并非总是如此 . 当我尝试检查链表中是否有一些字节,即(available()<1)时,程序只会卡住 . 否则,如果我不检查,我最终会从Arduino收到正确的字节响应
1 回答
浪费了4个小时后,我自己找到了答案 . 我最好使用
readBytes()
方法,其byteCount为1,timeOut为100ms只是为了安全起见 . 所以现在read方法看起来像这样 .