Writing to a Serial Port

The WriteFile function transfers data through the serial connection to another device. Before calling this function, an application must open and configure a serial port.

Because Windows CE does not support overlapped I/O—also called asynchronous I/O—the primary thread or any thread that creates a window should not try to write a large amount of data to a serial port. Such threads are blocked and cannot manage message queues. An application can simulate overlapped I/O by creating multiple threads to handle read/write operations. To coordinate threads, an application calls the WaitCommEvent function to block threads until specific communication events occur. For more information about communication events, see Using Communication Events.

    To write to a serial port

  1. Pass the port handle to the WriteFile function in the hFile parameter. The CreateFile function returns this handle when an application opens a port.
  2. Specify a pointer to the data to be written in lpBuffer. Often this data is binary data or a character array.
  3. Specify the number of characters to write in nNumberOfBytesToWrite. For Windows CE–based devices, usually one character is written because an application must convert Unicode characters to ASCII characters to enable text transfer to a device at the opposite end of a serial connection.
  4. Specify in lpNumberOfBytesWritten a pointer to the number of bytes actually written. WriteFile fills this variable so that an application can determine if the data transferred.
  5. Be sure that lpOverlapped is NULL.

The following code example shows how to transfer data using the WriteFile function.

DWORD dwError,
      dwNumBytesWritten;

WriteFile (hPort,              // Port handle
           &Byte,              // Pointer to the data to write 
           1,                  // Number of bytes to write
           &dwNumBytesWritten, // Pointer to the number of bytes 
                               // written
           NULL                // Must be NULL for Windows CE
);