// Code taken from
// https://www.pololu.com/docs/0J73/15.6
// and modified for my needs.
// modified for Linux
// gcc serialtestT_linux.c -O3 -Wall -s -o serialtest
// Frank B, 10/2021
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
// Opens the specified serial port, configures its timeouts, and sets its
// baud rate. Returns a handle on success, or INVALID_HANDLE_VALUE on failure.
int open_serial_port(const char * device, uint32_t baud_rate)
{
int fd = open(device, O_RDWR);
if (fd < 0) {
printf("could not open %s\n", device);
exit(1);
}
return fd;
}
// Writes bytes to the serial port, returning 0 on success and -1 on failure.
int write_port(int port, uint8_t * buffer, size_t size)
{
int r = write(port, buffer, size);
return r;
}
// Reads bytes from the serial port.
// Returns after all the desired bytes have been read, or if there is a
// timeout or other error.
// Returns the number of bytes successfully read into the buffer, or -1 if
// there was an error reading.
int read_port(int port, char * buffer, size_t size)
{
int n = read(port, buffer, size);
if (n < 0) {
printf("Failed to read from port");
exit(1);
}
return n;
}
int main(int argc, char **argv)
{
const char *device;
if ( argc != 2 ) {
fprintf(stderr, "Usage: %s COMx\n", argv[0]);
return 1;
}
device = argv[1];
printf("Port: %s\n", device);
uint32_t baud_rate = 9600;
int port = open_serial_port(device, baud_rate);
printf("After start, you'll probably see some garbage. Things will normalize after a few seconds.\n");
printf("Waiting...");
unsigned int lines = 0;
unsigned int pos = 0;
unsigned int lcnt = 0;
int r;
char line[256];
char buf[1000000];
memset(buf, 0, sizeof buf);
memset(line, 0, sizeof line);
do {
r = read_port(port, buf, 1);
//if (r) printf("%c", buf[0]);
} while( r < 1 || buf[0] != '\n' );
printf("Start.\n");
unsigned int gCnt = 0;
unsigned int zCnt = 1;
do {
r = read_port(port, buf, sizeof buf);
pos = 0;
while (r-- && pos < sizeof buf) {
char ch = buf[pos++];
if (lcnt < sizeof line) {
line[lcnt++] = ch;
}
if (ch == '\n') {
line[lcnt] = '\0';
if (lcnt != 64 || '1' != line[0] || 'z' != line[30] ) {
if ( lines == 100000) {
printf( "." );
fflush(stdout);
if ( !( gCnt % 50) )
printf("\nLines-Delta: %d. Received: %s", lines, line);
gCnt++;
}
else {
if ( 0 != zCnt ) {
printf("\nLines-Delta: %d. Received: %s", lines, line);
}
else {
printf( "._X" );
}
zCnt = lines;
}
lines = 0;
}
else lines++;
lcnt = 0;
}
}
} while (1);
close(port);
return 0;
}