简体   繁体   中英

How to read and write serial communication in Java?

I'm using this Java program to communicate with an Arduino board. However, I'm having trouble reading and writing serial data to the Arduino.

Currently it looks like this:

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());
        }
    }

I'm reading the input as a String and then converting a String reply to byte[] and replying. However this doesn't seem to be working. Can someone tell me a better way to do this? Maybe without converting byte[] to String and trying to interpret it.

Consider during a trim() on the String. You probably have extra whitespace (or a newline).

Also, you should check the return value of the read() method as it will return the actual bytes read (or -1) if there is a EOF. I mean it will probably work fine given that you do an available() call before it, but it's just a good habit to check these things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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