我正在编写必须与我的Arduino UNO通信的JavaFX应用程序。为此,我使用jSerialComm库。
出于测试目的,我已将一个非常简单的草图上载到Arduino,每2秒将一个“ Hello”字样打印到Serial:
void setup() {
//put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000);
Serial.print("Hello");
}
在我的JavaFX场景中,我使用以下命令读取传入的数据:
public void setDevice(SerialPort device) {
this.device = device;
device.openPort();
device.addDataListener(new SerialPortDataListener() {
@Override
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
}
@Override
public void serialEvent(SerialPortEvent serialPortEvent) {
if (serialPortEvent.getEventType() == SerialPort.LISTENING_EVENT_DATA_RECEIVED){
byte [] data = serialPortEvent.getReceivedData();
String msg = new String(data);
System.out.println(msg);
}
}
});
}
我可以从Arduino读取数据,但是它以一种奇怪的方式出现。就像字符串在2个不同的字符串中发送一样。这是控制台输出的图像:
难道我做错了什么?非常感谢你!
最佳答案
您在默认= NonBlocking模式下使用jSerialComm。所以发生了什么(作为伪代码步骤)
LISTENING_EVENT_DATA_RECEIVED triggered
get the char H
get the char e
Because we are nonBlocking we have to move on in the program
Print what we have so far -> HE
.... do other stuff or check if other stuff has to be processed
LISTENING_EVENT_DATA_RECEIVED triggered
get the char L
get the char L
get the char O
Because we are nonBlocking we have to move on in the program
Print what we have so far -> LLO
.... do other stuff or check if other stuff has to be processed
所以你可以做两件事->将模式更改为例如接收时阻塞(确保适当的超时以防止死锁)或重写函数(我的首选方式),以检查通信流中的终结符,然后处理缓冲区的内容(应以非阻塞方式实现)