1 #include <libserialport.h>
5 /* Example of how to wait for events on multiple ports.
7 * This example file is released to the public domain. */
9 /* Helper function for error handling. */
10 int check(enum sp_return result
);
12 int main(int argc
, char **argv
)
14 /* Get the port names from the command line. */
16 printf("Usage: %s <port name>...\n", argv
[0]);
19 int num_ports
= argc
- 1;
20 char **port_names
= argv
+ 1;
22 /* The ports we will use. */
23 struct sp_port
**ports
= malloc(num_ports
* sizeof(struct sp_port
*));
27 /* The set of events we will wait for. */
28 struct sp_event_set
*event_set
;
30 /* Allocate the event set. */
31 check(sp_new_event_set(&event_set
));
33 /* Open and configure each port, and then add its RX event
34 * to the event set. */
35 for (int i
= 0; i
< num_ports
; i
++) {
36 printf("Looking for port %s.\n", port_names
[i
]);
37 check(sp_get_port_by_name(port_names
[i
], &ports
[i
]));
39 printf("Opening port.\n");
40 check(sp_open(ports
[i
], SP_MODE_READ
));
42 printf("Setting port to 9600 8N1, no flow control.\n");
43 check(sp_set_baudrate(ports
[i
], 9600));
44 check(sp_set_bits(ports
[i
], 8));
45 check(sp_set_parity(ports
[i
], SP_PARITY_NONE
));
46 check(sp_set_stopbits(ports
[i
], 1));
47 check(sp_set_flowcontrol(ports
[i
], SP_FLOWCONTROL_NONE
));
49 printf("Adding port RX event to event set.\n");
50 check(sp_add_port_events(event_set
, ports
[i
], SP_EVENT_RX_READY
));
53 /* Now we can call sp_wait() to await any event in the set.
54 * It will return when an event occurs, or the timeout elapses. */
55 printf("Waiting up to 5 seconds for RX on any port...\n");
56 check(sp_wait(event_set
, 5000));
58 /* Iterate over ports to see which have data waiting. */
59 for (int i
= 0; i
< num_ports
; i
++) {
60 /* Get number of bytes waiting. */
61 int bytes_waiting
= check(sp_input_waiting(ports
[i
]));
62 printf("Port %s: %d bytes received.\n",
63 sp_get_port_name(ports
[i
]), bytes_waiting
);
66 /* Close ports and free resources. */
67 sp_free_event_set(event_set
);
68 for (int i
= 0; i
< num_ports
; i
++) {
69 check(sp_close(ports
[i
]));
70 sp_free_port(ports
[i
]);
76 /* Helper function for error handling. */
77 int check(enum sp_return result
)
79 /* For this example we'll just exit on any error by calling abort(). */
84 printf("Error: Invalid argument.\n");
87 error_message
= sp_last_error_message();
88 printf("Error: Failed: %s\n", error_message
);
89 sp_free_error_message(error_message
);
92 printf("Error: Not supported.\n");
95 printf("Error: Couldn't allocate memory.\n");