0% found this document useful (0 votes)
182 views

Creating A Serial Communication On Win32

Creating a Serial Communication on Win32 using mfc

Uploaded by

Kamal Ilam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
182 views

Creating A Serial Communication On Win32

Creating a Serial Communication on Win32 using mfc

Uploaded by

Kamal Ilam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

12,291,573 members (72,212 online)

articles

Q&A

ram84

forums

lounge

901 Sign out

Search for articles, questions, tips

Creating a Serial communication on Win32


konchat, 20 Oct 2002

CPOL

Rate:

4.55 (64 votes)


The purpose of this article is to describe how to interface to serial port on Win32.

Is your email address OK? You are signed up for our newsletters but your email address is either unconfirmed,
or has not been reconfirmed in a long time. Please click here to have a confirmation email sent so we can
confirm your email address and start sending you newsletters again. Alternatively, you can update your
subscriptions.

Download demo project - 12.4 KB


Download source - 33.4 KB

http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win

1/9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

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.


Creating a port handle
Restoring a configuration (DCB)
Modifying a configuration
Storing a configuration
Setting a Time-Out communication

Receive/Send data
Sending data
Receiving data
Closing a serial port

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 C
reateFilefunction. The following code shows the function that is used to create a handle:
Hide Copy Code

handlePort_ = CreateFile(portName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);

// Specify port device: default "COM1"


// Specify mode that open device.
// the devide isn't shared.
// the object gets a default security.
// Specify which action to take on file.
// default.
// default.

http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win

2/9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

As figure 2 shows, p
ortName= "COM1": the portNameis 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: C
reateFilefunction

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 G
etCommStatefunction 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:
Hide Copy Code

// 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:
Hide Copy Code

// Assign user parameter.


config_.BaudRate = dcb.BaudRate;
config_.StopBits = dcb.StopBits;
config_.Parity = dcb.Parity;
config_.ByteSize = dcb.ByteSize;

// Specify buad rate of communicaiton.


// Specify stopbit of communication.
// Specify parity of communication.
// 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:
http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win

3/9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

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 S
etCommStateAPI
function to store the configuration. The S
etCommStatefunction 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:
Hide Copy Code

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 C
OMMTIMEOUTSdata-structure and
calling S
etCommTimeoutsfunction. The code below shows setting time-out of communication:
Hide Copy Code

// 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
http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win

4/9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

// 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 R
eadFileoperation, the time period begins when the first character is received. If the interval between the
arrival of any two characters exceeds this amount, the R
eadFileoperation is completed and any buffered data is returned. A
value of zero indicates that interval time-outs are not used.
A value of M
AXDWORD, combined with zero values for both the ReadTotalTimeoutConstantand

ReadTotalTimeoutMultipliermembers, 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 R
eadTotalTimeoutMultipliermember and the requested number of bytes.
A value of zero for both the R
eadTotalTimeoutMultiplierand ReadTotalTimeoutConstantmembers
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 W
riteTotalTimeoutMultipliermember and the number of bytes to be
written.
A value of zero for both the W
riteTotalTimeoutMultiplierand WriteTotalTimeoutConstantmembers
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 W
riteFilefunction is a function used to send data in serial port communication.
Hide Copy Code
http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win

5/9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

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 R
eadFilefunction is the function that handles reading data in serial port communication.
Hide Copy Code

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 C
loseHandleAPI function to close handle of device control.
Hide Copy Code

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share
EMAIL

http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win

TWITTER

6/9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

About the Author


konchat
Web Developer
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.

You may also be interested in...


Serial communication for Win32 with modem
support

Cloud-based Data Warehousing as a Service,


Built for Analytics

Serial Communication in Windows

Capturing Customer Information from Driver's


Licenses using LEADTOOLS

Win32 SDK Serial Comm Made Easy

10 Ways to Boost COBOL Application


Development

Comments and Discussions

Add a Comment or Question

Search Comments

Go
First Prev Next

Thank You A Lot!


Carlos1907 26-Jun-14 1:44
http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win

7/9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

INVALID_HANDLE_VALUE for COM10 or higher fix


NZSmartie 23-Mar-14 3:48
How to get portnames
g8anush 2-Feb-14 22:27
Serial port reading is hanging
Member 10434756 29-Nov-13 12:20
VC++ 2010 Compile issue
MGreatwolf 13-Jan-13 19:01
Re: VC++ 2010 Compile issue
john_1726 27-Apr-15 12:09
My vote of 1
samdcvn 20-Sep-12 19:57
Re: My vote of 1
Carlos1907 26-Jun-14 0:39
My vote of 4
w-peuker 26-Jul-12 5:22
Re: My vote of 4
w-peuker 26-Jul-12 5:26
Re: My vote of 4
Vozzie2 2-Oct-12 7:23
Why does it not send my data to the port before I close the application
dgipling 5-Jul-12 9:42
Re: Why does it not send my data to the port before I close the application
Agnius Vasiliauskas 8-Jan-13 6:27
Want to display entire packet
Member 8262724 23-Sep-11 14:44
My vote of 5
Norm Heyder

25-Feb-11 16:32

serial communication
arvinder456 18-Nov-08 15:11
Detected memory leaks!
Bincker 16-Sep-08 3:43
Re: Detected memory leaks!
wct 2-Jan-09 8:51
Re: Detected memory leaks!
http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win
Bincker 9-Jan-09 1:50

8/9

5/25/2016

Creating a Serial communication on Win32 - CodeProject

Bincker

9-Jan-09 1:50

Re: Detected memory leaks!


wct 10-Jan-09 9:36
Re: Detected memory leaks!
Bincker 18-Jan-09 23:47
Is there a way to know the buffer size before reading it ?
joelparker 19-Aug-08 12:17
Way to close a comm port on which the handle has been lost?
Member 1929642 7-Aug-08 11:12
Re: Way to close a comm port on which the handle has been lost?
Raven1979933 5-Oct-08 1:59
how to execute in visual studio 2005 vc++
s123 9-Jul-08 14:55
Refresh
General

1 2 3 4 5 Next
News

Suggestion

Question

Bug

Answer

Joke

Praise

Rant

Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160518.1 | Last Updated 21 Oct 2002

Select Language
Layout: fixed | fluid

Article Copyright 2002 by konchat


Everything else Copyright CodeProject, 1999-2016

Enable UC auto page to scroll all the way down through pages! Enable

http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win

9/9

You might also like