我正在使用此Java program与Arduino板进行通信。但是,我在读取和写入Arduino的串行数据时遇到了麻烦。
目前它看起来像这样:
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
byte chunk[] = new byte[available];
input.read(chunk, 0, available);
String display = new String(chunk);
System.out.print(display);
if(display.equals("Request")) // Having problems with this line. not entering the loop even though I received the String "Request"
{
String reply = "Reply";
byte reply_byte[] = new byte[reply.length()];
reply_byte = reply.getBytes("UTF-16LE");
output.write(reply_byte);
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
我正在将输入作为String读取,然后将String回复转换为byte []并回复。然而,这似乎不起作用。有人能告诉我更好的方法吗?也许没有将byte []转换为String并尝试解释它。
答案 0 :(得分:1)
在字符串的trim()
期间考虑。你可能有额外的空格(或换行符)。
此外,您应该检查read()
方法的返回值,因为如果有EOF,它将返回读取的实际字节数(或-1)。我的意思是,如果你之前进行available()
调用它可能会很好,但检查这些东西只是一个好习惯。