-2

I'm new to c++ and windows serial communication. Now i'm following microsoft link., But there I don't know the meaning of following variables what's those variables do . Please help me to understand what the following variables. Variables i dont have idea

  1. ipBuf
  2. dwRead

code

DWORD dwRead;
BOOL fWaitingOnRead = FALSE;
OVERLAPPED osReader = {0};

// Create the overlapped event. Must be closed before exiting
// to avoid a handle leak.
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

if (osReader.hEvent == NULL)
   // Error creating overlapped event; abort.

if (!fWaitingOnRead) {
   // Issue read operation.
   if (!ReadFile(hComm, lpBuf, READ_BUF_SIZE, &dwRead, &osReader)) {
      if (GetLastError() != ERROR_IO_PENDING)     // read not delayed?
         // Error in communications; report it.
      else
         fWaitingOnRead = TRUE;
   }
   else {    
      // read completed immediately
      HandleASuccessfulRead(lpBuf, dwRead);
    }
}
  • ipBuf is the input buffer of size READ_BUF_SIZE bytes that should be allocated before calling ReadFile. dwRead returns the number of bytes actually read in this call. dw signifies a DWORD data type. – Prabindh Feb 07 '16 at 10:56

1 Answers1

0

In a nutshell, Windows API makes reading and writing to serial ports similar to reading/writing to any disk based file (CreateFile/ReadFile/WriteFile).

CreateFile is used actually used to "open the serial port" (meaning gaining exclusive access) since there isn't anything to really create.

ReadFile and WriteFile are rather self explanatory.

The one aspect that does cause confusion is the mode of operation - Overlapped and Non-Overlapped I/O. These mean the same as Asynchronous and Synchronous I/O respectively. Typically reading and writing to serial ports can take a variable duration of time to complete depending on factors such as the quantity of data that is actually available from the device or whether the device is still busy sending out the previous data to be sent. Overlapped I/O enables efficient waiting on tasks, by using "events" to signal back to the calling thread when tasks was completed.

Assuming you are writing a Win32 application (GUI/Console) you'd want to keep your application responsive to the user's input at all times. This means you'd want to go multi-threaded, one thread to handle the UI and the other to handle the communication. This communication thread can either use Overlapped I/O (complex, but more efficient in terms of CPU usage) or Non-Overlapped I/O (easier).

You might want to look at this library which claims to have a simpler interface http://www.naughter.com/serialport.html. I havent used it myself and hence cannot vouch for it.

Community
  • 1
  • 1
Shreyas Murali
  • 426
  • 2
  • 8
  • 14