• Use
serialport_read_until
to read data from a serial port. Pass it a file descriptor
and a buffer to be filled with the data read. The method also expects a
delimiter character, the maximum length of the buffer, and a timeout
value measured in milliseconds.
serial_port_read_until
stops reading when it
finds the delimiter character, when the buffer is full, or when it times out.
If it cannot read any more data before one of these conditions is met, it
returns -1. Otherwise, it returns 0.
• To make sure that all data you’ve written gets actually transferred, call
serialport_flush
and pass it the file descriptor of your serial port connection.
Here’s how to use the code for communicating with our analog reader sketch
(note that the following code will run on your PC and not on your Arduino):
SerialProgramming/C/analog_reader.c
#include <stdio.h>
Line 1
#include <unistd.h>
-
#include <termios.h>
-
#include "arduino-serial-lib.h"
-
#define MAX_LINE 256
5
-
int main(int argc, char* argv[]) {
-
int timeout = 1000;
-
-
if (argc == 1) {
10
printf("You have to pass the name of a serial port.\n");
-
return -1;
-
}
-
int baudrate = B9600;
-
int arduino = serialport_init(argv[1], baudrate);
15
if (arduino == -1) {
-
printf("Could not open serial port %s.\n", argv[1]);
-
return -1;
-
}
-
sleep(2);
20
char line[MAX_LINE];
-
while (1) {
-
int rc = serialport_write(arduino, "a0\n");
-
if (rc == -1) {
-
printf("Could not write to serial port.\n");
25
} else {
-
serialport_read_until(arduino, line, '\n', MAX_LINE, timeout);
-
printf("%s", line);
-
}
-
}
30
serialport_close(arduino);
-
return 0;
-
}
-
Appendix 3. Advanced Serial Programming • 258
report erratum • discuss
www.it-ebooks.info