Examples/Receiver-Arduino/receiver_serial.cxx

103 lines
2.8 KiB
C++
Raw Normal View History

2023-09-19 09:14:56 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <linux/ioctl.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <inttypes.h>
#include <fstream>
int openSerialPort(char* portname, int readMin=16){
/* Open the file descriptor in non-blocking mode */
int fd = open(portname, O_RDWR | O_NOCTTY);
if(fd==-1){
printf("Error trying to open the file: %s\n", portname);
return 1;
}
/* Set up the control structure */
struct termios toptions;
/* Get currently set options for the tty */
tcgetattr(fd, &toptions);
/* ----------- Set custom options ------------*/
/* 9600 baud */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* no hardware flow control */
toptions.c_cflag &= ~CRTSCTS;
/* enable receiver, ignore status lines */
toptions.c_cflag |= CREAD | CLOCAL;
/* disable input/output flow control, disable restart chars */
toptions.c_iflag &= ~(IXON | IXOFF | IXANY);
/* disable canonical input, disable echo, disable visually erase
* chars disable terminal-generated signals */
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
/* disable output processing */
toptions.c_oflag &= ~OPOST;
/* wait for readMin characters to come in before read returns */
/* WARNING! THIS CAUSES THE read() TO BLOCK UNTIL ALL */
/* CHARACTERS HAVE COME IN! */
toptions.c_cc[VMIN] = readMin;
/* no minimum time to wait before read returns */
toptions.c_cc[VTIME] = 0;
/* commit the options */
tcsetattr(fd, TCSANOW, &toptions);
/* Wait for the Arduino to reset */
usleep(1000*1000);
/* Flush anything already in the serial buffer */
tcflush(fd, TCIFLUSH);
printf("Ready to receive the words \n");
return fd;
}
void usage(){
printf("Read in loop a 32 bit word \n");
printf("I.e. it assumes that Arduino sends a 32 bit word for each readout\n");
printf("Usage: command portName \n");
exit(2);
}
void* out_stream;
void term_handler(int signal_num){
std::ofstream* out = static_cast<std::ofstream *>(out_stream);
//std::ofstream out = *out_point;
out -> flush();
out -> close();
exit(0);
}
int main(int argc, char *argv[]){
signal(SIGTERM, term_handler);
if(argc!=2)
usage();
// Set the port name
char* portName = argv[1];
int fd = openSerialPort(portName);
std::ofstream out("file.dat", std::ios::binary);
out_stream = &out;
for(;;){
uint32_t w = 0x0;
int n = read(fd, (char*) &w, 4);
printf("Got %d bytes, 0X%8x \n", n, w);
out.write ((char*) &w, sizeof(w));
}
out.close();
return 0;
}