First we import all the libraries we need, and we define a constant for the
maximum length of the lines we are going to read from the Arduino. Then we
define a
main
function.
After we’ve made sure that the name of a serial port was passed on the com-
mand line, we initialize a serial port in line 15. Then we sleep for two seconds
to give the Arduino some time to get ready. After that, we start a loop in line
23 where we constantly send the string “a0” to the Arduino. We check the
result of
serialport_write
, and if it was successful, we read the result sent by the
Arduino in line 27. Let’s compile our little program:
maik> gcc arduino-serial-lib.c analog_reader.c -o analog_reader
Determine what serial port your Arduino is connected to (mine is connected
to
/dev/tty.usbmodem24321
) and run the program like this:
maik> ./analog_reader /dev/tty.usbmodem24321
a0: 495
a0: 376
^C
Everything works as expected, and accessing a serial port using C isn’t that
difficult. To embed this code into a C++ program, you should wrap it in a
class named
SerialPort
or something similar.
Note that the arduino-serial library works on any POSIX-compatible system—in
other words, it won’t work on Windows.
Java
The Java platform standardizes a lot, and it also defines how to access a
serial port in the Java Communications API.
2
But the API is only a specification
that still has to be implemented. Unfortunately, there is no complete or even
perfect implementation available at the time of this writing.
For many years the RXTX project
3
provided a good implementation, but it
hasn’t been updated for a while now.
Oracle’s own implementation runs only on a few platforms, and the remaining
solutions are commercial products you have to pay for.
Fortunately, the jSSC (java-simple-serial-connector) project
4
comes to the
rescue. It doesn’t implement the Java Communications API, but it follows a
2.
http://www.oracle.com/technetwork/java/index-jsp-141752.html
3.
http://rxtx.qbang.org/
4.
https://code.google.com/p/java-simple-serial-connector/
report erratum • discuss
Serial Communication Using Various Languages • 259
www.it-ebooks.info