我正在編寫一個java程序,該程序通過rs232寫入命令並讀取溫度計的輸出。 我正在使用JSSC。寫入部分工作正常,但是當我讀取輸出並將其轉換爲字符串並使用System.out.println()打印時,會出現一些隨機的新行。當我用System.out.write()寫結果時,一切正常。 我檢查了字節碼,我沒有找到任何NL字符。讀取rs232時出現隨機新行rs232
繼承人我的代碼:
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");
}
}
}
}
下面是用的println outpout():
--- START (C) ---
21.0,
21.1,21.3,
21.1
21.0,
21.2,21.3,
21.2
而且具有寫入所需的輸出()
--- START (C) ---
21.0,21.1,21.3,21.1
21.0,21.1,21.3,21.1
你會說「你爲什麼不使用write()?「,但我需要將這個輸出轉換爲一個字符串。
有人可以幫助我嗎?
您想要的輸出中的溫度計是否在4個值之後發送換行符?你說它的期望輸出,但你想知道在熱舔回答你不期待換行符,我很困惑。 – Pedantic
是的,我可能已經解釋得很糟糕......我想在4個值之後有一個新的行。但是當我使用println()時,到處都是新線 – loics2