Question

I am using Hyperterminal to read an input from a sensor. This sensor sends out a string which should be in the form Value 6 digits or 5 digits and a decimal point(however it can come as 2 spaces and then 3 digits and one decimal) tab seperator Measurement unit("Ci","mCi" etc) tab seperator string eg(F-18 or C-11) tab Seperator tab CRLF strings end identifier.

If i monitor this input through Hyper terminal It reads it perfectly

0.00  kBq      F-18 2D

However when I read it I get broken segments of the string most of the time and sometimes I get the correct string an example of what I can get back is shown below.

0.00  k□□□□□□□□□□□□□

Bq      F-18 2D□□□□□□□□□

0.00  kBq      F-18 □□□

0.002D
□□□□□□□□□□

The code I use is from the RXTX library.

public void serialEvent (SerialPortEvent event){  
    if (event.getEventType()== SerialPortEvent.DATA_AVAILABLE){  
       byte[] readBuffer = new byte[19];  
       try{  
            while (inputStream.available() > 0){  
                int numBytes = inputStream.read(readBuffer);  
                }
       catch (IOException e) {}  
       input_line = new String (readBuffer);  
       inter.update(input_line);}}  
Was it helpful?

Solution

This is by design. You are assuming that you'll get all the bytes from the Read() call. That's not how it works, it will only give you the bytes that have been received so far. This happens in Hyperterminal as well, but you never notice because your eyes are not that quick.

You'll need to move readBuffer outside of the method and fill it progressively until you've received the full response. Then process it.

If the device only sends simple ASCII text and a line terminator, that's common, then calling SerialPort.ReadLine() is a good way to ensure you get all the characters in the response. Tweak the NewLine property if necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top