Java Reference
In-Depth Information
// Read low order byte
if ((input
=
fPortInStream.read ())
==
-1)
throw new IOException ();
fByteArray[3] = (byte)input;
ByteArrayInputStream fByteIn =
new ByteArrayInputStream (fByteArray);
DataInputStream fDataIn =
new DataInputStream (fByteIn);
return fDataIn.readInt ();
} // receiveInt
} // class GetJavalinData
The parameters in the constructor,
GetJavelinData (Outputable parent, int rate)
include the
rate
parameter that determines how often the data value from the
device is read. The other parameter is a reference to the
Outputable parent
that is used for “callbacks” to display messages sent via the
print (String)
and
println (String)
methods in the text area in the
SerialToJavelin
user interface.
The data from the sensor arrive over the serial port as a sequence of bytes.
Each pair of bytes must be converted to an
int
primitive value. We use
the techniques described in Chapter 9 in which a byte array becomes the
source for a
ByteArrayInputStream
,which in turn is wrapped with a
DataInputStream
class. The latter class offers the
readInt()
method that
returns an
int
value with the data bytes in the lower 2 bytes of the 4-byte
value.
Note that the code in
receiveInt()
in
GetJavelinData
expects the Java
standard big endian format in which the bytes arrive in order of the highest-order
byte first and the lowest-order byte last. So the Javelin must be programmed to
follow this format.
The loop in the
run()
method first sends the password, which here consists of
just a 2-byte value that matches a value set in the device program. If the password
is not accepted, the thread processing stops. Otherwise, the raw data value is read.
Then a “calibration” is done, which here simply consists of a slope and offset
correction. The
Outputable
reference provides a callback to the user interface
to print the temperature value.
Though many improvements and custom features can be added, this program
illustrates the essentials of communicating over the serial line with a device to
obtain data. In Chapter 24 we show how to set up the other end of the line with a
device that illustrates an application of embedded Java processors.
Search WWH ::
Custom Search