0

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.

dsolimano
  • 8,870
  • 3
  • 48
  • 63
ask
  • 2,160
  • 7
  • 31
  • 42
  • So if your string doesn't equal `"Request"`, what *does* it equal? If you're not sure, print out the value of all the bytes in `chunk`. – Greg Hewgill Jul 15 '12 at 05:12
  • My guess is your string is something like `Request\n`. Do a trim on the string. – Francis Upton IV Jul 15 '12 at 05:12
  • @Greg Hewgill: Sorry. Forgot to mention that I did receive the String "Request". As Francis said, trim() was required. – ask Jul 15 '12 at 08:13

1 Answers1

1

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.

Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57
  • Thanks! Silly me. I've encountered this same problem before when entries I took from a database had white space after them. – ask Jul 15 '12 at 08:12