I'm have been trying to write an code in C++ by using the Win32 API to communicate through the RS232 serial port with equipment. It's a simplex communication (only the equipment sends data in blocks of 289 bytes). I'm using an dedicated thread to read the serial port. Firstly I tried to use non-overlapped communication, but I realized that is impossible to close the serial port if there's no data incoming (the thread gets stuck on WaitCommEvent function). So I tried to use overlapped I/O and WaitForMultipleObjects to solve this problem:
I use the function SetEvent(SerialEvents); to close serial port on the main thread.
void *SerialRead(void *param) // param is a dummy pointer
memset( &overlapped, 0, sizeof(overlapped) );
overlapped.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
SerialEvents = overlapped.hEvent;
ReadFile(SerialPort, SerialBuffer, 289, &dwBytesRead, &overlapped);//Try to read 289 bytes
while (WaitForMultipleObjects(2, SerialEvents, false, INFINITE) == WAIT_OBJECT_0) //Wait for some event, if is an serial port event, executes de loop, if not, exit.
ReadFile(SerialPort, SerialBuffer, 289, &dwBytesRead, &overlapped); //Attempt to read the next 289 bytes
To open the serial port:
The problem is that even if I recive the 289 bytes, the thread keeps wating the function "WaitForMultipleObjects" return. If I recive the next 289 bytes the WaitForMultipleObjects function returns, but the data are mixed.
SerialPort = CreateFile(PortName,
GENERIC_READ|GENERIC_WRITE,//access ( read and write)
0, //(share) 0:cannot share the COM port
0, //security (None)
OPEN_EXISTING,// creation : open_existing
FILE_FLAG_OVERLAPPED, // overlapped I/O
0// no templates file for COM port...
Someone could help me?