Some Arduinos—for example, the Leonardo or the Micro—do not reboot upon
opening a serial connection. If you’re using one of these boards, your program
should wait until the serial stream is open:
Serial.begin(9600);
while (!Serial) ;
For some of the clients, you need to install additional libraries. In some cases,
you have to do that as an admin user on your machine. I won’t mention that
explicitly in the following sections. Also, you should make sure you don’t have
any serial monitor windows open when running one of the examples in the
following sections.
Finally, you should keep in mind that all sample programs show the bare
mechanics of serial port programming. In production code you’d at least check
whether the data you read back from the Arduino has the right format.
C/C++
Although you program the Arduino in C++, you don’t need to write clients
talking to the Arduino in C++ or C. Still, you can, and it’s easy if you use Tod
E. Kurt’s excellent
arduino_serial
1
as a basis.
The project implements a complete command-line tool offering a lot of useful
options. For our purposes, that’s not necessary. It’s sufficient to download
the files
arduino-serial-lib.h
and
arduino-serial-lib.c
.
The
arduino-serial
library exports the following functions:
•
serialport_init
opens a serial port connection. It expects the name of the
serial port to be opened and the baud rate to be used. It returns a file
descriptor if everything went fine, and it returns -1 otherwise.
• When you no longer need the serial port connection, you should close it
using
serialport_close
.
• With
serialport_writebyte
, you can send a single byte to an Arduino connected
to your computer’s serial port. Simply pass it the file descriptor returned
by
serialport_init
and the byte to be written. It returns -1 if an error occurred.
Otherwise, it returns 0.
•
serialport_write
writes an entire string to the serial port. It expects a file
descriptor and the string to be written. It returns -1 if an error occurred.
Otherwise, it returns 0.
1.
https://github.com/todbot/arduino-serial
report erratum • discuss
Serial Communication Using Various Languages • 257
www.it-ebooks.info