I'm working on a project where I get sensordata on an Arduino
which prints it over a Serial to my laptop. When I'm using the Arduino IDE this works fine with the Serial Monitor. (The full messages look like this: 1-35 251 58 152
). The characters after the -
are a UID, so they should always be the same as I am only testing with one device.
When I try to read this through Java I get different messages (or at least not complete ones).
public void setupUSB() {
SerialPort ports[] = SerialPort.getCommPorts();
for (SerialPort port : ports) {
if (port.getSystemPortName().equals("COM6")) myPort = port; // using LoRa over USB
}
myPort.setBaudRate(38400);
myPort.openPort();
myPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
}
The method above initiates the USB port which I am using. After some checks I try to read the port as following (removed try catch and other non-important code to this question).
Scanner data = new Scanner(myPort.getInputStream()).useDelimiter("\n");
if (data.hasNext()) {
String line = data.next();
System.out.println("readUSB: " + line);
}
I have also tried the following:
Scanner data = new Scanner(myPort.getInputStream());
if (data.hasNextLine()) {
String line = data.nextLine();
System.out.println("readUSB: " + line);
}
The results which I'm getting from the System.out.println("readUSB: " + line);
are as follows:
readUSB: �
readUSB: 152
readUSB: 9-35 251 58 152
readUSB: 152
readUSB: 1-35 251 58 152
readUSB: 5 251 58�152
readUSB: 251 58 152
readUSB:
readUSB: 58 152
As you see (there is some noise in the messages), most of these messages are not complete.
Could anyone tell me what causes this and how to fix it?
[EDIT]
As I am using LoRa to transfer the data from one sensor to another Arduino, I'm collecting the data as chars. Both of the Arduino's and my USB port use the same baudRate at 38400
. I feel like the error could be in the code below, as when I hook up the sensor USB (instead of sending it over LoRa) the values are actually correct.
if (packetFound) {
// Print the packet over Serial per character
Serial.println();
for (int i=0; i<19; i++) { //20 and 21 are squares
Serial.print(char(RxData[i]));
RxData[i] = 0x00; // Clear buffer [0x20 -> space]
}
}