I’m working on a java program that writes commands and reads output of a thermometer through rs232.
I’m using JSSC. The writing part works fine, but when I’m reading the output and convert it to String and print it with System.out.println(), some random new lines appear. When I write the result with System.out.write(), everything is working fine.
I checked the bytecode, and I didn’t found any NL character.
Heres my code:
public boolean openPort(int rate, int databits, int stopbit, int parity){
try {
serialPort.openPort();
serialPort.setParams(rate, databits, stopbit, parity);
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
serialPort.setEventsMask(mask);//Set mask
serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener
return true;
} catch (SerialPortException e) {
System.out.println(e);
return false;
}
}
static class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR()){//If data is available
try {
byte buffer[] = serialPort.readBytes(event.getEventValue());
//with system.out.write
try {
System.out.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//with system.out.println
String readed = new String(buffer);
System.out.println(readed);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
else if(event.isCTS()){//If CTS line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("CTS - ON");
}
else {
System.out.println("CTS - OFF");
}
}
else if(event.isDSR()){///If DSR line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("DSR - ON");
}
else {
System.out.println("DSR - OFF");
}
}
}
}
Here’s the outpout with println():
--- START (C) ---
21.0,
21.1,21.3,
21.1
21.0,
21.2,21.3,
21.2
And the desired output with write()
--- START (C) ---
21.0,21.1,21.3,21.1
21.0,21.1,21.3,21.1
You’ll say “why don’t you just use write()?”, but I need to convert this output to a string.
Can someone help me?
printlnadds a newline character at the end. To not add that, useprint.