listen from serial

This commit is contained in:
Alexander Popov 2023-07-29 22:32:44 +03:00
parent bdd87110c1
commit afd878407e
Signed by: iiiypuk
GPG Key ID: E47FE0AB36CD5ED6
6 changed files with 111 additions and 1 deletions

View File

@ -0,0 +1,6 @@
[{clear,build,format-code}]
indent_style = space
indent_size = 4
[*.c]
indent_size = 2

View File

@ -1,7 +1,11 @@
# libserialport examples
port_info.c
list_ports.c
send_receive.c
# binaries
port_info
list_ports
send_receive
listen

View File

@ -10,6 +10,8 @@ export LIBRARY_PATH=$HOME/Git/libserialport/.libs
for file in \
port_info.c \
list_ports.c \
send_receive.c \
listen.c \
do
gcc -static -Wall -O3 -o ${file%.*} $file -lserialport

View File

@ -4,4 +4,14 @@
#
# Alexander Popov <iiiypuk@fastmail.fm>
rm port_info
files=(
"port_info"
"list_ports"
"send_receive"
"listen"
)
for file in ${files[@]}
do
rm $file &> /dev/null
done

14
~/C/libserialport/format-code Executable file
View File

@ -0,0 +1,14 @@
#!/bin/sh
#
# formt-code - script for beautify code by clang-format.
#
# Alexander Popov <iiiypuk@fastmail.fm>
files=(
"listen.c"
)
for file in "${files[@]}"
do
clang-format -i --style=LLVM --sort-includes=false $file
done

View File

@ -0,0 +1,74 @@
#include <libserialport.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Helper function for error handling. */
int check(enum sp_return result);
int main(int argc, char **argv) {
int result;
const int size = 30;
char *buffer = malloc(size + 1);
const char *port_name = "/dev/ttyACM0";
const unsigned int timeout = 1000;
struct sp_port *serial_port;
check(sp_get_port_by_name(port_name, &serial_port));
printf("Opening port.\n");
check(sp_open(serial_port, SP_MODE_READ_WRITE));
printf("Setting port to 9600 8N1, no flow control.\n");
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));
result =
check(sp_blocking_write(serial_port, "ping", strlen("ping"), timeout));
while (1) {
result = check(sp_blocking_read(serial_port, buffer, size, timeout));
if (result == -1) {
printf("Error reading from serial port\n");
break;
} else if (result == 0) {
printf("No more data\n");
break;
} else {
buffer[result] = '\0';
printf("=====\n%s\n", buffer);
}
}
free(buffer);
}
/* Helper function for error handling. */
int check(enum sp_return result) {
/* For this example we'll just exit on any error by calling abort(). */
char *error_message;
switch (result) {
case SP_ERR_ARG:
printf("Error: Invalid argument.\n");
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:
printf("Error: Not supported.\n");
abort();
case SP_ERR_MEM:
printf("Error: Couldn't allocate memory.\n");
abort();
case SP_OK:
default:
return result;
}
}