Mikhail
Mikhail

Reputation: 8028

Wait for data on COM port?

I'm looking for a way to get a Windows serial port to timeout until it has received data. It would be nice if there was some kind of event that triggered or a function to do exactly what I want.

This is my current implementation.

void waitforCom(unsinged char byte)
{
   while (true)
   {
      ClearCommError(serial_handle, &errors, &status);
      if (status.cbInQue>0)
      {
         //check if correct byte
         break;
      }
   }
}

Upvotes: 2

Views: 4519

Answers (3)

Preston
Preston

Reputation: 2653

Another API call you could be using is WaitCommEvent().

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363479(v=vs.85).aspx

This call can work asynchronously since it takes an OVERLAPPED object as a parameter. In your case you'd want to simply wait on the EV_RXCHAR event to let you know data has arrived:

OVERLAPPED o = {0};
o.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

SetCommMask(comPortHandle, EV_RXCHAR);

if (!WaitCommEvent(comPortHandle, &commEvent, &o))
{
    // Check GetLastError for ERROR_IO_PENDING, if I/O is pending then
    // use WaitForSingleObject() to determine when `o` is signaled, then check
    // the result. If a character arrived then perform your ReadFile.
}

Alternatively you could do the same thing by having a thread with an outstanding ReadFile call, but using the OVERLAPPED object instead of blocking as MSalters recommends.

Upvotes: 3

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10415

At the winAPI level, for most applications you need to dedicate a thread to serial port input because ReadFile is a blocking call (but with a timeout). The most useful event you can get is having ReadFile return. Just put ReadFile in a loop in a thread and generate your own event or message to some other thread when ReadFile gets some data.

Upvotes: 0

Paweł Stawarz
Paweł Stawarz

Reputation: 4012

I'm not really a specialist when it comes to WinApi, but there's a whole article on the Microsoft Developer Network, that covers the subject of serial communications. The article mentions the subject of waiting for the data from a port, and it's supplied with an example.

Upvotes: 1

Related Questions