Home > Back-end >  Serial Comunnication between Java and Arduino
Serial Comunnication between Java and Arduino

Time:04-23

I'm writing a code to send and receive data using the serial port of an arduino, for that I'm using the jserialcomm library. For sending and receiving data, I'm using a DataListener of the library which detect whether or not a bunch of bytes has been sent or received, the problem is that DataListener uses a method called getListneningEvents to list the events which the the DataListener will be able to use, but you can only return one of them because is overwriting an abstract method who returns only one integer, the documentation says that you can return one or more events but I trully don't know how to do it, if you can help with that pls.

public class MessageListener implements SerialPortMessageListener{
@Override
public int getListeningEvents() { 
    return SerialPort.LISTENING_EVENT_DATA_WRITTEN;
    // return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
    // I want to return both methods
}


@Override
public byte[] getMessageDelimiter(){ 
    return new byte[] {
        (byte)0x0A
    }; 
}

@Override
public boolean delimiterIndicatesEndOfMessage(){ 
    return true; 
}

@Override
public void serialEvent(SerialPortEvent event){
    switch (event.getEventType()) {
        //Evento para datos enviados
        case SerialPort.LISTENING_EVENT_DATA_WRITTEN:
            System.out.println("All bytes were successfully transmitted!");
            break;
        
        //Evento para datos recibidos
        case SerialPort.LISTENING_EVENT_DATA_RECEIVED:
            byte[] delimitedMessage = event.getReceivedData();
            String mensaje = new String(delimitedMessage, StandardCharsets.UTF_8);
            mensaje = mensaje.replace("\n", "");
            System.out.println("Received the following delimited message: "   mensaje);
            break;
    }
    
}

}

Documentation of that DataListener

CodePudding user response:

You can listen for multiple events by OR'ing these together:

return SerialPort.LISTENING_EVENT_DATA_WRITTEN | SerialPort.LISTENING_EVENT_DATA_RECEIVED;

How this works:

Assume LISTENING_EVENT_DATA_WRITTEN has the value 1 and LISTENING_EVENT_DATA_RECEIVED has the value 2, in binary:

1 = 01
2 = 10

If these two numbers are now OR'ed together using the logical OR operator |, the result is:

01 | 10 = 11

The library now checks if

11 & LISTENING_EVENT_DATA_WRITTEN == LISTENING_EVENT_DATA_WRITTEN

if this is the case, this is "passed on" to your class

  • Related