91 lines
1.9 KiB
C
91 lines
1.9 KiB
C
#include <libserialport.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <stdbool.h>
|
|
|
|
/* Helper function for error handling. */
|
|
int check(enum sp_return result);
|
|
|
|
int main(int argc, char **argv) {
|
|
struct sp_port *serial_port;
|
|
char *port_name = "/dev/ttyACM0";
|
|
|
|
const int size = 256;
|
|
char *buffer = malloc(size + 1);
|
|
|
|
const unsigned int timeout = 1000;
|
|
int result;
|
|
|
|
if (argc != 2) {
|
|
printf("Usage: %s <port>\n", argv[0]);
|
|
return -1;
|
|
} else {
|
|
port_name = argv[1];
|
|
}
|
|
|
|
printf("Connecting to '%s'...\n", port_name);
|
|
check(sp_get_port_by_name(port_name, &serial_port));
|
|
check(sp_open(serial_port, SP_MODE_READ_WRITE));
|
|
|
|
check(sp_set_baudrate(serial_port, 9600));
|
|
check(sp_set_bits(serial_port, 8));
|
|
check(sp_set_parity(serial_port, SP_PARITY_NONE));
|
|
check(sp_set_stopbits(serial_port, 1));
|
|
check(sp_set_flowcontrol(serial_port, SP_FLOWCONTROL_NONE));
|
|
puts("Connected.");
|
|
|
|
|
|
while (true) {
|
|
int pos = 0;
|
|
|
|
while (pos < size) {
|
|
result = check(sp_blocking_read(serial_port, buffer + pos, 1, timeout));
|
|
|
|
if (result == -1) {
|
|
puts("Error reading from serial port");
|
|
break;
|
|
} else if (result == 0) {
|
|
puts("No more data");
|
|
break;
|
|
} else {
|
|
if (buffer[pos] == '\n') {
|
|
buffer[pos] = '\0';
|
|
break;
|
|
} else
|
|
pos++;
|
|
}
|
|
|
|
puts(buffer);
|
|
}
|
|
}
|
|
|
|
free(buffer);
|
|
|
|
return 0;
|
|
}
|
|
|
|
/* Helper function for error handling. */
|
|
int check(enum sp_return result) {
|
|
char *error_message;
|
|
|
|
switch (result) {
|
|
case SP_ERR_ARG:
|
|
puts("Error: Invalid argument.");
|
|
abort();
|
|
case SP_ERR_FAIL:
|
|
error_message = sp_last_error_message();
|
|
printf("Error: Failed: %s\n", error_message);
|
|
sp_free_error_message(error_message);
|
|
abort();
|
|
case SP_ERR_SUPP:
|
|
puts("Error: Not supported.");
|
|
abort();
|
|
case SP_ERR_MEM:
|
|
puts("Error: Couldn't allocate memory.");
|
|
abort();
|
|
case SP_OK:
|
|
default:
|
|
return result;
|
|
}
|
|
}
|