Click here to Skip to main content
Click here to Skip to main content

Creating a Serial communication on Win32

, 20 Oct 2002
Rate this:
Please Sign up or sign in to vote.
The purpose of this article is to describe how to interface to serial port on Win32.
Sample Image

Introduction

The purpose of this article is to describe how to interface to serial port on Win32. The serial port can be implemented by several techniques such as ActiveX, access I/O and file operation. This article explains the use of serial port on Win32 platform by file operation technique. The programmer can use kernel32.lib library that is provided with the Microsoft Visual C++ Version 6.0. In Microsoft Windows (2000, Me, XP and 95/98), serial port can be treated as a file. Therefore it's possible to open a serial port by using Windows file-creating function.

This article explains not only about serial port communication but also how to implement multi-tasking that can apply with our project "serial port" application. The reason why the software (serial communication) will be implemented with multi-tasking method is that the serial communication application has to handle work with more than one task at the same time. For example data-reading task, data-sending task, GUI task etc.

These topics describe the basic operation of interfacing a serial port on Win32:

Initial/Open serial port communication.

Receive/Send data

Design approach

Initial/Open serial port

The first step in opening a serial port is initiation or setting a serial port's configuration. The purpose of this is to create the serial port agent. All throughout the article we are going to use a file handle as serial port agent.

Creating a port handle

The serial port's handle is a handle that can be used to access the object of serial port. The function that is used to create the serial port handle is the CreateFile function. The following code shows the function that is used to create a handle:

handlePort_ = CreateFile(portName,  // Specify port device: default "COM1"
GENERIC_READ | GENERIC_WRITE,       // Specify mode that open device.
0,                                  // the devide isn't shared.
NULL,                               // the object gets a default security.
OPEN_EXISTING,                      // Specify which action to take on file. 
0,                                  // default.
NULL);                              // default.

As figure 2 shows, portName = "COM1": the portName is a variable that is declared by const char*. It is used to specify port name that wants to create a serial port handle.

Figure 2: CreateFile function

Restoring a configuration

The restoration of serial port configuration is getting current configuration at control device. The configuration of serial port includes parameters that are used for setting a serial communications device.

The GetCommState function is used to get the current device-control and then fills to a device-control block (a DBC structure) with the current control settings for a specified communications device. The following code shows the function that is used to get the current control device:

// Get current configuration of serial communication port.
if (GetCommState(handlePort_,&config_) == 0)
{
   AfxMessageBox("Get configuration port has problem.");
   return FALSE;
}

Modifying a configuration

When you already have serial port configuration in the DBC format, you have to modify parameters a bit. Following code shows the parameters modified:

// Assign user parameter.
config_.BaudRate = dcb.BaudRate;  // Specify buad rate of communicaiton.
config_.StopBits = dcb.StopBits;  // Specify stopbit of communication.
config_.Parity = dcb.Parity;      // Specify parity of communication.
config_.ByteSize = dcb.ByteSize;  // Specify  byte of size of communication.
  • DWORD BaudRate:

    Current baud rate (default = 9600)

  • BYTE StopBits:

    0,1,2 = 1, 1.5, 2 (default = 0)

  • BYTE Parity:

    0-4= no, odd, even, mark, space (default = 0)

  • BYTE ByteSize:

    Number of bits/byte, 4-8 (default = 8)

Note: Recommend that programmers use default value for typical communication. As shown in figure 3, Watch Dialog Box shows the default values that are used for typical communication.

Figure 3: Serial port configuration

Storing a configuration

The next step is the storage of new configuration that is modified already into device control. Call SetCommState API function to store the configuration. The SetCommState function configures a communications device according to the specifications in a device-control block (a DBC structure). The function reinitializes all hardware and control settings, but it does not empty output or input queues. Following code shows storage of a new configuration:

if (SetCommState(handlePort_,&config_) == 0)
{
  AfxMessageBox("Set configuration port has problem.");
  return FALSE;
}

Setting a Time-Out communication

The final step in serial port opening is setting communication Time-out by using the COMMTIMEOUTS data-structure and calling SetCommTimeouts function. The code below shows setting time-out of communication:

// instance an object of COMMTIMEOUTS.
COMMTIMEOUTS comTimeOut;                   
// Specify time-out between charactor for receiving.
comTimeOut.ReadIntervalTimeout = 3;
// Specify value that is multiplied 
// by the requested number of bytes to be read. 
comTimeOut.ReadTotalTimeoutMultiplier = 3;
// Specify value is added to the product of the 
// ReadTotalTimeoutMultiplier member
comTimeOut.ReadTotalTimeoutConstant = 2;
// Specify value that is multiplied 
// by the requested number of bytes to be sent. 
comTimeOut.WriteTotalTimeoutMultiplier = 3;
// Specify value is added to the product of the 
// WriteTotalTimeoutMultiplier member
comTimeOut.WriteTotalTimeoutConstant = 2;
// set the time-out parameter into device control.
SetCommTimeouts(handlePort_,&comTimeOut);
ReadIntervalTimeout

Specifies the maximum time, in milliseconds, allowed to elapse between the arrival of two characters on the communications line. During a ReadFile operation, the time period begins when the first character is received. If the interval between the arrival of any two characters exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used.

A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the characters that have already been received, even if no characters have been received.

ReadTotalTimeoutMultiplier

Specifies the multiplier, in milliseconds, used to calculate the total time-out period for read operations. For each read operation, this value is multiplied by the requested number of bytes to be read.

ReadTotalTimeoutConstant

Specifies the constant, in milliseconds, used to calculate the total time-out period for read operations. For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes.

A value of zero for both the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant members indicates that total time-outs are not used for read operations.

WriteTotalTimeoutMultiplier

Specifies the multiplier, in milliseconds, used to calculate the total time-out period for write operations. For each write operation, this value is multiplied by the number of bytes to be written.

WriteTotalTimeoutConstant

Specifies the constant, in milliseconds, used to calculate the total time-out period for write operations. For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written.

A value of zero for both the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that total time-outs are not used for write operations.

Note: After the user has set the time-out of communication without any error, the serial port has opened already.

Sending data

Most of data transmission of serial port is done as writing a file. Programmer can apply file operation functions for sending data to serial port. The WriteFile function is a function used to send data in serial port communication.

if (WriteFile(handlePort_,   // handle to file to write to
    outputData,              // pointer to data to write to file
    sizeBuffer,              // number of bytes to write
    &length,NULL) == 0)      // pointer to number of bytes written
{
    AfxMessageBox("Reading of serial communication has problem.");
    return FALSE;
}

Note: If the function succeeds, the return value is nonzero.

Receiving data

Most of data reception of serial communication is done as reading a file. Programmer can apply file operation functions for receiving data from serial port. The ReadFile function is the function that handles reading data in serial port communication.

if (ReadFile(handlePort_,  // handle of file to read
    inputData,               // handle of file to read
    sizeBuffer,              // number of bytes to read
    &length,                 // pointer to number of bytes read
    NULL) == 0)              // pointer to structure for data
{
    AfxMessageBox("Reading of serial communication has problem.");
    return FALSE;
}

Note: If the function succeeds, the return value is nonzero.

Closing a serial port

The serial port closing calls the CloseHandle API function to close handle of device control.

if(CloseHandle(handlePort_) == 0)    // Call this function to close port.
{
    AfxMessageBox("Port Closeing isn't successed.");
    return FALSE;
}

Note: If the function succeeds, the return value is nonzero.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

konchat
Web Developer
United States United States
I am living in Thailand, I am working as a Software Engineer at a transportation Compay, In my spare time I like to play ping pong.
 
My programming experience includes C/C++, Java, C#, Assembler(Intel/Motolora), MFC, ATL, OpenGL, a bit for HTML.

Comments and Discussions

 
GeneralThank You A Lot! PinmemberCarlos190725-Jun-14 20:44 
QuestionINVALID_HANDLE_VALUE for COM10 or higher fix PinmemberNZSmartie22-Mar-14 22:48 
QuestionHow to get portnames Pinmemberg8anush2-Feb-14 17:27 
QuestionSerial port reading is hanging PinmemberMember 1043475629-Nov-13 7:20 
QuestionVC++ 2010 Compile issue PinmemberMGreatwolf13-Jan-13 14:01 
Hi,
 
I am trying to compile the source in Visual Studio VC++ 2010. When I do this I get the following error:
 
error LNK2001: unresolved external symbol "public: static struct CRuntimeClass * __stdcall SerialThread::GetThisClass(void)" (?GetThisClass@SerialThread@@SGPAUCRuntimeClass@@XZ)
 
I have narrowed it down to the following line of code in SearialAppDlg.cpp:
 
serialProcess = (SerialThread*)AfxBeginThread(RUNTIME_CLASS(SerialThread), THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
 
For some reason the compiler does not like the cast to "SerialThread*". Can someone please help me sort through this.
 
Thanks in advance.
GeneralMy vote of 1 Pinmembersamdcvn20-Sep-12 14:57 
GeneralRe: My vote of 1 PinmemberCarlos190725-Jun-14 19:39 
GeneralMy vote of 4 Pinmemberw-peuker26-Jul-12 0:22 
GeneralRe: My vote of 4 Pinmemberw-peuker26-Jul-12 0:26 
GeneralRe: My vote of 4 [modified] PinmemberVozzie22-Oct-12 2:23 
QuestionWhy does it not send my data to the port before I close the application Pinmemberdgipling5-Jul-12 4:42 
AnswerRe: Why does it not send my data to the port before I close the application PinmemberAgnius Vasiliauskas8-Jan-13 1:27 
QuestionWant to display entire packet PinmemberMember 826272423-Sep-11 9:44 
GeneralMy vote of 5 PinmemberNorm Heyder25-Feb-11 11:32 
Generalserial communication Pinmemberarvinder45618-Nov-08 10:11 
GeneralDetected memory leaks! PinmemberBincker15-Sep-08 22:43 
GeneralRe: Detected memory leaks! Pinmemberwct2-Jan-09 3:51 
GeneralRe: Detected memory leaks! PinmemberBincker8-Jan-09 20:50 
GeneralRe: Detected memory leaks! Pinmemberwct10-Jan-09 4:36 
GeneralRe: Detected memory leaks! PinmemberBincker18-Jan-09 18:47 
QuestionIs there a way to know the buffer size before reading it ? Pinmemberjoelparker19-Aug-08 7:17 
QuestionWay to close a comm port on which the handle has been lost? PinmemberMember 19296427-Aug-08 6:12 
AnswerRe: Way to close a comm port on which the handle has been lost? PinmemberRaven19799334-Oct-08 20:59 
Questionhow to execute in visual studio 2005 vc++ Pinmembers1239-Jul-08 9:55 
AnswerRe: how to execute in visual studio 2005 vc++ PinmemberCem Usta7-Dec-09 2:39 
Questionhow to retrieve the data from USB Pinmembersukumarvenkata2-Jun-08 3:47 
Questionhow to read data from a serial port Pinmembersamifiaz2k30-Jul-07 2:35 
NewsMemory management... Pinmembereqda25-Jun-07 22:37 
GeneralI can't communicate serial port without any other serial communication program run first PinmemberTony MicroCode11-May-07 4:27 
QuestionRe: I can't communicate serial port without any other serial communication program run first PinmemberChip select11-Jun-07 8:59 
GeneralRe: I can't communicate serial port without any other serial communication program run first Pinmemberkmike019-Oct-07 23:50 
GeneralIcon question PinmembereRose245-Feb-07 11:05 
GeneralSome questions on this program Pinmemberlobo4life3-Feb-07 17:02 
QuestionWhat if SetCommState is jammed? PinmemberMember #25944795-Jan-07 15:15 
Generalfurther support about transfering file PinmemberDevilno12-Nov-06 18:02 
Generalask about thread Pinmemberlibbey20-Sep-06 18:13 
Generalserial com in java PinmemberBharat_sb21-Jun-06 21:25 
GeneralRe: serial com in java PinmemberZeulance11-Jul-06 7:10 
GeneralRe: Bharat PinmemberBharat_sb11-Jul-06 18:28 
GeneralRe: Bharat PinmemberYiannis Hatzopoulos18-Jun-08 2:45 
QuestionHow to deal with PS/2 Keyboard ? PinmemberThuan_pham4-Apr-06 16:26 
QuestionDissapearing lines when closing port Pinmemberwvdm23-Mar-06 9:39 
Generalproblem when send and receive some blocks of data PinmemberThuan_pham12-Mar-06 16:43 
GeneralHelp me C++ Pinmember英雄1-Aug-05 17:19 
Generali cant build it Pinmemberptsanche4-Jul-04 14:53 
GeneralRe: i cant build it Pinmembersgallo12-Jul-04 9:22 
GeneralRe: i cant build it Pinmemberokaljuvee19-Jan-06 19:46 
AnswerRe: i cant build it PinmemberCem Usta7-Dec-09 2:50 
AnswerRe: i cant build it Pinmemberseobi495-May-08 16:10 
GeneralRe: i cant build it PinmemberxSIZARx7-Feb-11 1:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.141015.1 | Last Updated 21 Oct 2002
Article Copyright 2002 by konchat
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid