Reading from a Serial Port

An application calls the ReadFile function to receive data from a device at the other end of a serial connection. ReadFile takes the same parameters as the WriteFile function.

Typically, a read operation is a separate thread that is always ready to process data arriving at a serial port. A communication event signals the read thread that there is data to read at a serial port. The thread usually reads one byte at a time—one ReadFile call for each byte—until all of the data is read. Then the read thread waits for another communication event.

For more information about communication events, see Using Communication Events.

    To read from a serial port

  1. Pass the port handle to ReadFile in the hFile parameter. The CreateFile function returns this handle when an application opens a port.
  2. Specify a pointer to receive the data that is read in lpBuffer.
  3. Specify the number of characters to read in nNumberOfBytesToRead.
  4. Specify a pointer to the number of bytes actually read in lpNumberOfBytesRead.
  5. Be sure that lpOverlapped is NULL. Windows CE does not support overlapped I/O.

The following code example shows how to receive data using the ReadFile function.

BYTE Byte;
DWORD dwBytesTransferred;

ReadFile (hPort,                // Port handle
          &Byte,                // Pointer to data to read
          1,                    // Number of bytes to read
          &dwBytesTransferred,  // Pointer to number of bytes
                                // read
          NULL                  // Must be NULL for Windows CE
);