CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2013

    [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:

    void *SerialRead(void *param)  // param is a dummy pointer
    	OVERLAPPED overlapped;
    	memset( &overlapped, 0, sizeof(overlapped) );
    	overlapped.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
    	SerialEvents[0] = 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.
    		//Do stuff
    		ReadFile(SerialPort, SerialBuffer, 289, &dwBytesRead, &overlapped); //Attempt to read the next 289 bytes
    	return 0;
    I use the function SetEvent(SerialEvents[1]); to close serial port on the main thread.

    To open the serial port:

    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...
    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.

    Someone could help me?

  2. #2
    Join Date
    Dec 2013

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.