最近要写个小项目,接收串口发来的数据,然后发给前端展示实时曲线。因为咱也不会C#,只能用java来了,使用RXTXcomm库写了个demo,源码感兴趣的可以自己去搜一下,这里只讲遇到的问题。
用串口模拟工具测试发消息 还好好的 一整条接收过来。然后用实际的板子测试,发过来的数据是一条一条的 看图:
这数据肯定是不对的,前端接到这数据怎么显示,肯定是不行的,原因可能是因为串口是异步数据,一根线既可以发消息,也可以接收消息,三四根线各发各的。
解决办法:
添加个线程,sleep一下。
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这个sleep时间可以自己调整。
while里的完整代码:
try {
int numBytes = -1;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = new String(readBuffer);
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
if (numBytes > 0) {
msgQueue.add(new String(readBuffer));
String message = new String(readBuffer, 0, numBytes, "UTF-8");
MqttGateway mqttGateway = (MqttGateway) SpringAware.getContext().getBean("mqttGateway");
mqttGateway.sendToMqtt(message, "straingage");
readBuffer = new byte[1024];// 重新构造缓冲对象,否则有可能会影响接下来接收的数据
} else {
msgQueue.add("额---------没有读到数据");
}
}
} catch (IOException e) {
}
好了 现在这个数据才是正常的数据,前端才能正常使用。