Direct Serial Communication
My primary task for this assignment was to research methods of communication with devices connected to the serial port using the language of C. The first method that I came across was a very direct method. It was coupled with a discussion of serial modems as well.
First, we would need to open a connection to the serial port, which was accomplished by using the following C code:
int port;
port = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
Then, there were various configurations that needed to be made. These included setting the baud rate to 9600, setting the character length to 8 characters, setting the stop bit length to 1, and disabling the parity bit. These were all contained in the “termios” structure in the C header “termios.h”.
//Pointer to the termios structure in termios.h
struct termios config;
//Gets the current configuration for the port
tcgetattr(port, &config);
//Set the baud rate to 9600
cfsetispeed(&config, B9600);
cfsetospeed(&config, B9600);
//Enable the receiver, set local mode
config.c_cflag |= (CLOCAL | CREAD);
//Only one stop bit
config.c_cflag &= ~CSTOP;
//No Parity
config.c_cflag &= ~PARENB;
//Setting the Character size to 8
config.c_cflag &= ~CSIZE;
config.c_cflag |= CS8;
//Set the new options for the port
tcsetattr(port, TCSANOW, &config);
Although this method seemed to make sense, we were unable to open the correct port. For some reason, the Linux machine would only open port 3, which is incorrect. We solved this using a much simpler method of communication.
System Calls in C
Using Linux, we were able to directly communicate with the serial port without using an interface program. We had a simple command that could be called from the command line. In the file “unistd.h”, there is a system() function that takes a string and runs it as a command on the Linux terminal. Using this method, we were able to bypass opening and configuring the port and simply make the system calls automatically. The C code is as follows:
system( "N02 > /dev/ttyS0") ;
This accomplishes our goal of communicating with the serial port using C. Using a simple loop, we tested this on the Linux box with a LED and two fans. I am a bit concerned about the timing of the calls and intend to research further the issues with the initial code we found. The system calls seem to slow down as execution time increases, and timing will be critical when we are measuring the liquids.