//talk to serial ports in RAW mode - ie 8 bits for data etc // log events in a logfile // KM July 2003 // version 1.1 #include #include #include #include #include #include #define BYTE unsigned char // GLOBAL variables for simplicity int serialport; // serial port int outfile; // where we write log files to FILE *logfd; // log file char mesg[512]; // somewhere to make logfile strings! //---------------------- HELPERS------------------------- BYTE getbyte () { BYTE byte; read (serialport, &byte, 1); return byte; } // write a byte BYTE putbyte(BYTE b) { return(write(serialport, &b, 1)); } // write a string int putstring(char *s) { int l = strlen(s); //log(s); if ( write(serialport, s, l) != l) return(-1); else return(0); } // print message to log file void logfile(char *str) { fprintf(logfd, str); fflush(logfd); } // print error message to log file and exit erexit(char *str) { fprintf(logfd, str); // exit is a bit severe - means we'd have to restart externally exit(1); } //-------------------- INITIALISE----------------- // open serial port for raw byte transfers // open log file // caller needs to include termios.h to get the speed types like B9600,B57600 // caller needs to close the files if necessary // initialise_coms(char *serialportname, speed_t serial_speed, char *logfilename) { struct termios term; // open log file for appending logfd = fopen(logfilename, "a"); if( logfd == NULL) erexit("failed to open log file!"); // now the serial port serialport = open (serialportname, O_RDWR | O_NOCTTY ); if (serialport == -1) erexit ("can not open serial port!\n"); if( tcgetattr(serialport, &term) == -1) erexit("getattr failed!"); // set BAUD rate cfsetospeed(&term, serial_speed); cfsetispeed(&term, serial_speed); cfmakeraw(&term); // Set the serial port mode NOW if( tcsetattr(serialport, TCSANOW, &term) == -1) erexit("setattr failed!"); logfile("initialised OK\n"); }