A serial port is a communication physical interface through which information transfers in or out one bit at a time (in contrast to a parallel port) being, more or less compliant, with the RS-232 standard.
But serial port communications aren't only useful for wired DE-9 connectors. it also allows us to use it with USB (ftdi), Bluetooth (serial profile) and Zigbee using virtual serial ports.
·
Serial and virtual serial ports appear as COMx in Windows operating systems (COM1, COM2, ...) andin UNIX/Linux as ttySx or ttyUSBx or even ttyACMx (ttyS0, ttyS1, ttyUSB0, ttyUSB1, ttyACM0, ttyACM1,...).
For programming purposes we usually want to communicate computers with others computers, microcontrollers or other devices like GPS, LED or LCD displays.
·
Serial port programming in C/C++, Windows and Linux
Using the serial port is a lot easier, but sometimes tricky. The basic commands are to open a connection, read and write over this connection and, finally, tom close it, better if using the C++ RAII idiom.
Windows commands:
Here you can find a complete C++ for Windows example.
With these next two definitions (among others needed):
HANDLE
serialPortHandle
wchar_t
* device
- Opening a connection, CreateFile:
serialPortHandle = CreateFile(device, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);
if (serialPortHandle!=INVALID_HANDLE_VALUE)
ReadFile(serialPortHandle, buffer, len, &read_nbr, NULL);
...
if (serialPortHandle!=INVALID_HANDLE_VALUE)
WriteFile(serialPortHandle, buffer, len, &result, NULL);
- Closing the connection, CloseHandle
CloseHandle(serialPortHandle);
Unix/Linux commands:
Here you can find a complete C++ for Linux example.
With these two definitions:
·
int
fileDescriptor;
char
*device;
·
·
- Opening a connection, open
struct termios terminalAttributes;
fileDescriptor = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_FSYNC );
// clear terminalAttributes data
memset(&terminalAttributes, 0, sizeof(struct termios));
terminalAttributes.c_cflag = B57600 | CS8 | CLOCAL | CREAD;
terminalAttributes.c_iflag = IGNPAR | ONLCR;
terminalAttributes.c_oflag = OPOST;
terminalAttributes.c_cc[VTIME] = 0;
terminalAttributes.c_cc[VMIN] = 1;
tcsetattr(fileDescriptor, TCSANOW, &terminalAttributes);
int
n=read(fileDescriptor, buffer, len);
...
int
n=write(fileDescriptor, buffer, len);
- Closing the connection, close
close(fileDescriptor);
More information:
https://en.wikipedia.org/wiki/Serial_communication
http://en.wikipedia.org/wiki/Serial_port
http://www.lvr.com/serport.htm
http://digilander.libero.it/robang/rubrica/serial.htm
http://en.wikibooks.org/wiki/Serial_Programming
http://msdn.microsoft.com/en-us/library/ff802693.aspx