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.
·
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.
Here you can find a complete C++ for Windows example.
With these next two definitions (among others needed):
HANDLE serialPortHandlewchar_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);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);intn=read(fileDescriptor, buffer, len);
...
intn=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