从没有<cr> </cr>的Scale串口获取数据

时间:2014-03-31 09:16:50

标签: java string serial-port

我试图使用串口从秤中读取重量。 但我想我接收数据并且我不知道如何在没有

的情况下打印数据

我的连续剧事件:

public void serialEvent(SerialPortEvent event){
        switch(event.getEventType()) {
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                outputBufferEmpty(event);
                break;

            case SerialPortEvent.DATA_AVAILABLE:
                byte[] readBuffer = new byte[20];
                try {
                     int numBytes = inputStream.read(readBuffer);
                     String str = new String (readBuffer, "UTF-8");
                     ok+=str;
                     //System.out.print(str);
                     System.out.println();
                     System.out.print(ok.replaceAll("\\s+", ""));
                     //System.out.print(str.replace("\n", "").replace("\r", ""));
                    } catch (IOException ex) {}
                break;

        } 
    }

我尝试了所有。 但这是我现在的输出:

0
0                 0
0                 0                 0
0                 0                 0                 .
0                 0                 0                 .                 0
0                 0                 0                 .                 0                 5
0                 0                 0                 .                 0                 5                 0
0                 0                 0                 .                 0                 5                 0

我想要这个:  000.050 KG

这是我的规模协议:

Scale Protocol

欲了解更多信息,我的规模是:Mettler Toledo VIVA或OHAUS RV系列

2 个答案:

答案 0 :(得分:2)

为什么不尝试直接加倍?

import java.nio.ByteBuffer;

public static double toDouble(byte[] bytes) {
    return ByteBuffer.wrap(bytes).getDouble();
}

答案 1 :(得分:1)

我猜答案是:

您从整个20字节字节数组创建了一个字符串,而不是您刚读取的部分。

将创建字符串的行更改为:

String str = new String(readBuffer, 0, numBytes, "UTF-8")

输出中的额外间隙可能是由数组末尾的空字节引起的,尽管很难确定没有关于您使用的输出设备类型的详细信息(不重要)