December 29th, 2013, 04:45 PM
[RESOLVED] Overlapped serial comunication
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?
December 31st, 2013, 07:34 AM
Re: Overlapped serial comunication
I discovered the problem. It was that on setup when openning the serial port I was calling GetCommState() function before SetCommState(), so it was overwriting the DCB structure configuration, setting a wrong baud rate value. I fix it and now it's working wonderfully!
Tags for this Thread
Click Here to Expand Forum to Full Width
This a Codeguru.com survey!