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
function.
main
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
, and if it was successful, we read the result sent by the
serialport_write
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
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.
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
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
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/
Serial Communication Using Various Languages
) and run the program like this:
2
3
provided a good implementation, but it
www.it-ebooks.info
But the API is only a specification
4
comes to the
259
report erratum
discuss
Need help?
Do you have a question about the Arduino Uno and is the answer not in the manual?