Click here to Skip to main content
12,951,619 members (63,914 online)
Rate this:
Please Sign up or sign in to vote.
See more:
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

1 solution

Rate this: bad
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,
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
    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();
    case WAIT_TIMEOUT :
        // No data received during specified wait time
        nErr = WAIT_TIMEOUT;
    case WAIT_FAILED :
        nErr = ::GetLastError();
// 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.

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

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 6,229
CHill60 3,490
Maciej Los 3,083
Jochen Arndt 1,975
ppolymorphe 1,880

Advertise | Privacy | Mobile
Web02 | 2.8.170525.1 | Last Updated 22 Dec 2012
Copyright © CodeProject, 1999-2017
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