Here's some example code for initializing a serial port. I used this class for simple (no flow control or handshaking) serial communications.
SerialConnection::SerialConnection(string port_name, BaudRate baud, Parity parity, DataBits data_bits, StopBits stop_bits)
{
old_dcb = new DCB; //Pointers for Get/SetCommState
new_dcb = new DCB;
COMMTIMEOUTS timeout;
if (port_name != "COM1" && port_name != "COM2" && port_name != "COM3" && port_name != "COM4" )
throw WBException(WBException::INV_PORT_NAME);
port = CreateFile( port_name.data(),
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
0,
0);
if (port == INVALID_HANDLE_VALUE)
throw WBException(WBException::SER_PORT_ERR);
GetCommState(port, old_dcb);
*new_dcb = *old_dcb;
new_dcb->BaudRate = (baud ? CBR_9600 : CBR_4800);
new_dcb->ByteSize = (data_bits ? 8 : 7);
new_dcb->fParity = (parity ? EVENPARITY : NOPARITY);
new_dcb->StopBits = (stop_bits ? TWOSTOPBITS : ONESTOPBIT);
new_dcb->fOutxDsrFlow = 0;
new_dcb->fOutxCtsFlow = 0;
new_dcb->fDsrSensitivity = 0;
SetCommState(port, new_dcb);
timeout.ReadIntervalTimeout = 500;
timeout.ReadTotalTimeoutMultiplier = 100;
timeout.ReadTotalTimeoutConstant = 100;
SetCommTimeouts(port, &timeout);
}
And this is the sending function:
int SerialConnection::Send(const char* send_block, int length)
{
DWORD bytes_written;
for (int i = 0; i < length; ++i)
{
WriteFile(port, send_block, 1, &bytes_written, NULL);
send_block++;
if (bytes_written < 1)
throw WBException(WBException::SER_PORT_ERR);
Sleep(100);
}
return bytes_written;
}