byte currentByte = serialPort.readBytes(1)[0];
while (currentByte != NEWLINE) {
line[i++] = currentByte;
currentByte = serialPort.readBytes(1)[0];
}
return new String(line);
}
}
Although this program defines a class named
AnalogReader
, it’s not very object-
oriented. We only define it because everything in Java has to live in a class
context.
The
main
function implements the protocol for our Arduino sketch. First, we
make sure that the name of a serial port was set on the command line. Then
we use this name to initialize a new
SerialPort
object. To open the serial port,
we call the
openPort
method. After a two-second pause, we configure the serial
port’s parameters.
In the loop that follows, we send the string “a0” to the serial port using
Serial-
Port
’s
writeString
method. Afterward, we read the result by invoking the
readLine
function and print it to the console.
Currently, jSSC doesn’t offer a readLine function, so we have to write our
own. The function reads the Arduino’s response byte by byte using the
readBytes
method, because jSSC doesn’t offer a method for reading a single byte.
readLine
appends all bytes read to the byte array named
line
until it detects a newline
character (ASCII code 10). Finally, it converts the byte array into a
String
object
and returns it.
Here’s how to compile and use the program:
maik> javac -cp jssc.jar AnalogReader.java
maik> java -cp jssc.jar:. AnalogReader /dev/tty.usbmodem24321
a0: 496
a0: 433
a0: 328
a0: 328
^C
AnalogReader
does exactly what it’s intended to do: it permanently prints the
values of the analog pin 0. Accessing a serial port in Java is a piece of cake
if you use the right libraries.
Note that jSSC also allows you to write object-oriented code. It has a
Serial-
PortEventListener
interface that makes it easy to decouple the handling of serial
report erratum • discuss
Serial Communication Using Various Languages • 261
www.it-ebooks.info