繁体   English   中英

如何用Java读写串行通信?

[英]How to read and write serial communication in Java?

我正在使用此Java程序与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());
        }
    }

我将输入读取为字符串,然后将字符串回复转换为byte []并回复。 但是,这似乎不起作用。 有人可以告诉我更好的方法吗? 也许无需将byte []转换为String并尝试对其进行解释。

在对String进行trim()时考虑。 您可能有多余的空格(或换行符)。

另外,您应该检查read()方法的返回值,因为如果有EOF,它将返回读取的实际字节(或-1)。 我的意思是,鉴于您在此之前进行了available()调用,它可能会正常工作,但这只是检查这些事情的好习惯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM