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
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
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
Port
s
writeString
method. Afterward, we read the result by invoking the
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
method, because jSSC doesn t offer a method for reading a single byte.
appends all bytes read to the byte array named
character (ASCII code 10). Finally, it converts the byte array into a
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
interface that makes it easy to decouple the handling of serial
PortEventListener
Serial Communication Using Various Languages
AnalogReader
SerialPort
object. To open the serial port,
line
www.it-ebooks.info
, it s not very object-
Serial-
readLine
readBytes
readLine
until it detects a newline
String
object
Serial-
261
report erratum
discuss
Need help?
Do you have a question about the Arduino Uno and is the answer not in the manual?