Click here to Skip to main content
11,705,208 members (52,211 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
Dear sir/mam,

I am using read function for reading the serial data using mfc2008. It is working fine. But when i am using same function in while(1) loop it waits for the data. Logically it is correct. But i want to ignore the read function if it is not getting the data with in 1 second and go to the next line.
How it is possible???????Please help me.
Posted 21-Dec-12 21:20pm
Anshuta371

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

You may use overlapped I/O. Untested code snippet:
// Open port, initialize port, create events
// Serial port must be opened in overlapped mode
HANDLE hCom = ::CreateFile(lpszPort, GENERIC_READ | GENERIC_WRITE,
    0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
HANDLE hEvRead = ::CreateEvent(NULL, TRUE, FALSE, NULL);
 
// Read data inside while loop
DWORD nErr = 0;
DWORD nRead = 0;
char Buffer[BUF_SIZE];
OVERLAPPED ov = {0};
ov.hEvent = hevRead;
if (!::ReadFile(hCom, &Buffer, sizeof(Buffer), &nRead, &ov))
    nErr = ::GetLastError();
// Data has not been read yet
if (nErr == ERROR_IO_PENDING)
{
    nErr = 0;
    // Wait 1000 milliseconds
    switch (::WaitForSingleObject(hevRead, 1000))
    {
    case WAIT_OBJECT_0 :
        // Check for read errors
        if (!::GetOverlappedResult(hCom, &ov, &nDone, FALSE))
            nErr = ::GetLastError();
        break;
    case WAIT_TIMEOUT :
        // No data received during specified wait time
        nErr = WAIT_TIMEOUT;
        break;
    case WAIT_FAILED :
        nErr = ::GetLastError();
        break;
    }
}
// Process data if nErr == 0

This code should be called from a worker thread because the thread may be blocked for 1 second when no data arrive.

An alternative is to use a worker thread checking for EV_RXCHAR serial events using SetCommMask() and WaitCommEvents(). Then you are waiting for the event that is fired when at least one character is available for reading.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 535
1 OriginalGriff 284
2 ppolymorphe 126
3 Andy Lanng 125
4 F-ES Sitecore 110
0 OriginalGriff 8,958
1 Sergey Alexandrovich Kryukov 8,276
2 CPallini 5,189
3 Maciej Los 4,726
4 Mika Wendelius 3,606


Advertise | Privacy | Mobile
Web03 | 2.8.150819.1 | Last Updated 22 Dec 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100