문제

Im trying to read the weight from a scale using the serial port. But i think i'm receiving data with and i don't know how to print it without the

My serial event:

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;

        } 
    }

I tried all. But this is my output now:

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

And I want this: 000.050 KG

This is the protocol of my scale:

Scale Protocol

For more information my scale is: Mettler Toledo VIVA or an OHAUS RV Series

도움이 되었습니까?

해결책 2

I guess the answer is:

You created a string from the entire 20-byte byte array, rather than the portion that you just read.

Change the line that creates the string to:

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

The extra gaps in your output were probably caused by the null-bytes from the end of the array, although it's hard to know for sure without details on what type of output device you were using (not that important)

다른 팁

Why dont u try to make it directly to double?

import java.nio.ByteBuffer;

public static double toDouble(byte[] bytes) {
    return ByteBuffer.wrap(bytes).getDouble();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top