9.2 SERIAL COMMUNICATIONS UNDER LINUX
In Linux serial communications is similar to normal file access. The file names used to access these ports are in the 'dev' directory. The 'com1' port is called 'ttyS0', and the 'com2' port is called 'ttyS1'.
int fd; /* File Descriptor Global Variable */
Figure X.10 - The Header File (serial_io.h)
int param_parity; // not implemented yet
int param_flow; // not implemented yet
serial_io::serial_io(char *args){
param_baud = B9600; // set defaults
for(i = 0; (i < len) && (error == NO_ERROR); i++){
error = decode_param(&(temp[last]));
error = decode_param(&(temp[last]));
if((error == NO_ERROR) && (param_file_name != NULL)){
if((fd = open(param_file_name /*args[0] port "/dev/ttyS0"*/, O_RDWR | O_NOCTTY | O_NDELAY)) < 0){
printf("Unable to open serial port\n");
fcntl(fd, F_SETFL, FNDELAY);
/* Configure port reading */
/* Get the current options for the port */
cfsetispeed(&options, param_baud); /* Set the baud */
cfsetospeed(&options, param_baud);
options.c_cflag |= (CLOCAL | CREAD);
// enable receiver and set local mode
options.c_cflag &= ~PARENB;
// Mask the character size to 8 bits, no parity
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= param_size;
// set number of data bits
// options.c_cflag &= ~CRTSCTS;
// Disable hardware flow control
// options.c_lflag &= ~(ICANON | ECHO | ISIG);
options.c_oflag |= OPOST;
tcsetattr(fd, TCSANOW, &options);
serial_io::~serial_io(void)
if(param_file_name != NULL) delete param_file_name;
int serial_io::decode_param(char*parameter){
if(param_file_name != NULL) delete param_file_name;
param_file_name = new char[strlen(parameter)];
strcpy(param_file_name, &(parameter[1]));
} else if(parameter[0] == 'B'){
temp = atoi(&(parameter[1]));
if(temp == 9600) param_baud = B9600;
if(temp == 2400) param_baud = B2400;
if(temp == 1200) param_baud = B1200;
} else if(parameter[0] == 'D'){
temp = atoi(&(parameter[1]));
if(temp == 8) param_size = CS8;
if(temp == 7) param_size = CS7;
printf("Did not recognize serial argument type - ignoring\n");
int serial_io::reader(char *text, int max){
char_read = read(fd, text, max-1);
for(i = 0; i < char_read;){
if((text[i] == 10 /*CR*/) || (text[i] == '\n')){
for(j = i+1; j <= char_read; j++){
} else if(text[i] == '\t'){
printf("Serial port is not initialized\n");
int serial_io::writer(char *text)
for(count = 0; count < length; count++){
write(fd, &(text[count]), 1);
printf("Serial port not initialized\n");
Figure X.11 - Serial Communication Drivers (serial_io.c)
serial = new serial_io("B9600,F/dev/ttyS0");
if(serial->reader(in, 100) != ERROR){
printf("Got String: %s", in);
sprintf(out, "ECHO: %s\n", in);
printf("Sending String: %s", out);
Figure X.12 - A Serial Communication Program (serial.c)
These programs can be compiled with the makefile in Figure X.13.
serial: serial.c serial_io.o
$(CC) $(CFLAGS) serial.c -o serial serial_io.o
serial_io.o: serial_io.c serial_io.h
$(CC) $(CFLAGS) -c serial_io.c
Figure X.13 - A Makefile