Use Win32 API to create a serial communication program

Source: Internet
Author: User

Use Win32 to create a serial communication program
Author: konchat
Translation: powercpp

Download the sample code in this article

Introduction:
This article describes how to process serial ports in Win32. Serial communication can be achieved through a variety of technologies, such as ActiveX, I/O access and file operations. This article describes how to use serial ports through file operations on the Win32 platform. Programmers can use kernel32.lib provided by Microsoft Visual C ++ version 6.0. In Microsoft Windows (2000, me, XP and 95/98), the serial port is used as the file processing. Therefore, you can use the Windows File Creation function to open the serial port.

This article not only introduces the serial communication, but also introduces how to implement multi-task in the serial communication application. Multi-task can enable the serial communication application to process more tasks at the same time, for example: read data tasks, send data tasks, Gui tasks, and so on.

The following topic describes basic serial port operations in Win32:

Initialize/enable Serial Communication

  • Create a port handle
  • Get configuration (DCB)
  • Modify configurations
  • Save Configuration
  • Set communication timeout

Receive/send data

  • Send data
  • Receive data
  • Close serial port

Design steps:

Initialize/open the serial port

The first step to open the serial port is to initialize or set the serial port configuration to create a serial port proxy. We will use the file handle as the serial port proxy throughout the article.

Create a port handle

A serial handle is a serial object handle that can be accessed. The createfile function is used to create a serial handle, as shown in the following code:

Handleport _ = createfile (portname, // port device: Default "COM1" generic_read | generic_write, // device open mode: allow read/write 0, // do not share null, // Default Security Settings: open_existing, // open mode: Open the existing port 0, // default null); // default

2. portname = "COM1": portname indicates a const char * variable, which specifies the name of the port to create the serial port handle.

Figure 2: createfile Function

Get Configuration

Obtain the current configuration from the control device. The configuration contains parameters used to set the serial communication device.

You can use the getcommstate function to get the current device configuration and fill in the device control block (DCB structure) with the current configuration of the specified communication device, as shown in the following code:

// Obtain the current configuration of the serial port if (getcommstate (handleport _, & config _) = 0) {afxmessagebox ("Get Configuration Port has problem."); Return false ;}

Modify configurations

When you have obtained the serial port configuration in the DCB structure, you should modify the parameters, as shown in the following code:

// Specify the USER parameter config _. baudrate = DCB. baudrate; // baud rate config _. stopbits = DCB. stopbits; // stop bit config _. parity = DCB. parity; // parity check config _. bytesize = DCB. bytesize; // data bit
  • DWORD baudrate:

    Baud Rate (default = 9600)

  • Byte stopbits:

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

  • Byte parity:

    0-4 = none, odd, even, sign, space (default = 0)

  • Byte bytesize:

    Data bit, 4-8 (default = 8)

For typical communication, it is recommended that programmers use the default value. As shown in figure 3, the watch dialog box displays the default values for typical communication.

Figure 3: Serial Port Configuration

Save Configuration

The next step is to save the modified configuration to the device control. Call the setcommstate API function to save the configuration. Setcommstate function: configure the communication device in the device control block (DCB structure. This function initializes all hardware control settings, but does not empty the input/output queue. The Code is as follows:

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

Set communication timeout

The last step to enable the port is to use the commtimeouts data structure and call the setcommtimeouts function to set the communication timeout. The following code is used:

// Commtimeouts object commtimeouts comtimeout; // maximum latency between two characters: comtimeout. readintervaltimeout = 3; // read the timeout value of each byte comtimeout. readtotaltimeoutmultiplier = 3; // fixed read Serial Port Data timeout // total timeout = readtotaltimeoutmultiplier * number of bytes + readtotaltimeoutconstantcomtimeout. readtotaltimeoutconstant = 2; // write timeout comtimeout per byte. writetotaltimeoutmultiplier = 3; // fixed timeout comtimeout for writing serial data. writetotaltimeoutconstant = 2; // write the timeout parameter to the device control setcommtimeouts (handleport _, & comtimeout );

Readintervaltimeout

Specifies the maximum latency of two characters on the communication line, in milliseconds. During the readfile operation, the time period starts from the receipt of the first character. If the interval between two received characters exceeds this value, the readfile operation is complete and all buffered data is returned. This value does not work if readintervaltimeout is 0.

If the value is maxdword and the values of readtotaltimeoutconstant and readtotaltimeoutmultiplier are both 0, the read operation returns immediately with the received character, even if no character is received.

Readtotaltimeoutmultiplier

Indicates the cumulative value in milliseconds. Used to calculate the total number of read operation timeouts. For each read operation, this value is multiplied by the number of bytes to be read.

Readtotaltimeoutconstant

A constant in milliseconds. Used to calculate the total number of read operation timeouts. For each read operation, readtotaltimeoutmultiplier is multiplied by the number of bytes to be read and then added to this value.

If both readtotaltimeoutmultiplier and readtotaltimeoutconstant are 0, the total number of timeouts is ignored during the read operation.

Writetotaltimeoutmultiplier

Indicates the cumulative value in milliseconds. Used to calculate the total number of times-out during write operations. For each write operation, this value is multiplied by the number of bytes to be written.

Writetotaltimeoutconstant

A constant in milliseconds. Used to calculate the total number of times-out during write operations. For each write operation, writetotaltimeoutmultiplier is multiplied by the number of bytes to be written and then added to the value.

If both writetotaltimeoutmultiplier and writetotaltimeoutconstant are 0, the total number of timeouts is ignored during write operations.

Tip: If no error occurs after the user sets the communication timeout, the serial port is enabled.

Send data

Serial Data Transmission is mostly used for writing files. programmers can use file operation functions to send data to the serial port. Use the writefile function to send data to the serial port.

If (writefile (handleport _, // file handle outputdata, // data buffer pointer sizebuffer, // number of bytes & length, null) = 0) // pointer {afxmessagebox ("reading of serial communication has problem. "); Return false ;}

Tip: if the function is successful, a non-0 value is returned.

Receive data

Serial Port Data is mostly processed as read files. Programmers can use file operation functions to receive data from the serial port. Use the readfile function to receive data from the serial port.

If (readfile (handleport _, // handle inputdata, // data buffer pointer sizebuffer, // number of bytes & length, // point to the number of bytes read null) = 0) // overlapped I/O struct {afxmessagebox ("reading of serial communication has problem. "); Return false ;}

Tip: if the function is successful, a non-0 value is returned.

Close serial port

You can call the closehandle API function to disable the serial port.

If (closehandle (handleport _) = 0) // call this function to close the serial port {afxmessagebox ("port closeing isn' t successed."); Return false ;}

Tip: if the function is successful, a non-0 value is returned.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.