VC + + Serial Communication programming detailed

Source: Internet
Author: User

Under Win32, you can use two kinds of programming to implement serial communication, one is to use ActiveX control, this method is simple, but less flexible. The second is to call the Windows API function, this method can clearly grasp the mechanism of serial communication, and free and flexible. The following is a description of the API serial communication content.

The operation of the serial port can be operated in two ways: synchronous operation mode and overlapping operation mode (also known as asynchronous operation mode). When synchronizing, the API function blocks until the operation is complete (in multithreaded mode, although it does not block the main thread, but still blocks the listener), and the API function returns immediately after the operation is performed in the background, avoiding thread blocking.

However, regardless of the way of operation, generally through the following four steps to complete:

(1) Open the serial port;

(2) Configure the serial port;

(3) Read and write serial port;

(4) Close the serial port;

1. Open the serial port

The WIN32 system extends the concept of a file. Whether it's a file, a communication device, a named pipe, a mail slot, a disk, or a console, it is opened or created using the API function CreateFile. The prototype of this function is:

1 HANDLE CreateFile (2 3LPCTSTR lpFileName,//need to open the serial port logical name, such as "COM3"45DWORD dwDesiredAccess,//Specify the type of access for the serial port, read, write, or coexist, read: Generic_read, write: Generic_write6 7DWORD dwShareMode,//specifies a shared property, but the serial port cannot be shared, the parameter must be 08 9Lpsecurity_attributes lpSecurityAttributes,//Reference security property structure, default value is nullTen  OneDWORD Dwcreationdistribution,//Create flag, this parameter must be open_existing for serial port operation A  -DWORD dwFlagsAndAttributes,//Property Description, which specifies whether the serial port is synchronous or asynchronous, which is file_flag_overlapped, which represents the use of asynchronous I/O; the value is 0, which indicates synchronous I/O operations; -  theHANDLE hTemplateFile//This parameter is NULL for the serial port -  -);

2. Configure the serial port

After opening the handle of the communication device, some initialization configuration is required for the serial port. This needs to be done through a DCB structure. The DCB structure contains information such as baud rate, number of data bits, parity, and stop bits. The DCB structure is used as a buffer when querying or configuring the properties of the serial port.

Usually after opening the serial port with CreateFile, call the Getcommstate function to get the initial configuration of the serial port. When you want to modify the configuration of the serial port, you should modify the DCB structure before calling the SetCommState function to set the serial port.
DCB structure contains the parameters of the serial port settings, the following are only a few of the variables commonly used in this structure:

1typedefstruct_dcb{2DWORD baudrate,//baud rate: 9600, 115200, etc.3DWORD Fparity,//specifies parity, which is 1 o'clock, allows parity4BYTE ByteSize,//communication byte bit, 4-8-bit5BYTE Parity,//Specify the method of parity, evenparity parity, noparity no checksum, markparity mark Check, oddparity odd check6BYTE StopBits,//specify the number of bits in the stop bit: Onestopbit, on 5STOPBITS, Twostopbits7};
DCB Structure

The Getcommstate function can get the device control block of the COM port to obtain the relevant parameters, the prototype is as follows

12     //3     // pointer to a device control block (DCB structure) 4   

The SetCommState function sets the device control block for the COM port, and the prototype is:

12     // handle identifying the communication port 3     LPDCB LPDCB// point to a device control block 4  );  

In addition to the settings in DCB, the program generally needs to set the I/O buffer size and timeout.

Windows uses I/O buffers to stage data for serial input and output. If the rate of communication is high, you should set a larger buffer. Call the Setupcomm function to set the size of the input and output buffers for the serial port. The prototype is as follows:

12     //3     //  size of input buffer (bytes)4       the size of the//output buffer (bytes)5  );  

When reading and writing serial ports with ReadFile and WriteFile, you need to consider the timeout problem.

The function of a timeout is to not read or send a specified number of characters within a specified amount of time, and the operation of ReadFile or WriteFile will still end. To query the current time-out setting should call the Getcommtimeouts function, which populates a commtimeouts structure. The setcommtimeouts can set a timeout with the contents of a COMMTIMEOUTS structure.

There are two types of timeouts for read-write serial ports: Interval timeout and total timeout. The interval timeout is the maximum delay between two characters at the time of receipt. The total timeout is the maximum time a read-write operation has taken. The write operation only supports the total timeout, while both the read operation timeout is supported.

The COMMTIMEOUTS structure can be used to specify the timeout for read and write operations, with the following prototype:

1typedefstruct_commtimeouts {2DWORD ReadIntervalTimeout;//Read interval timeout3DWORD ReadTotalTimeoutMultiplier;//Read Time factor4DWORD ReadTotalTimeoutConstant;//Read Time Constants5DWORD WriteTotalTimeoutMultiplier;//Write Time Factor6DWORD writetotaltimeoutconstant;//Write Time Constants7} commtimeouts,*lpcommtimeouts;

  The members of the COMMTIMEOUTS structure are in milliseconds. The calculation formula for the total timeout is:

Total Timeout = time factor x number of characters required to read/write + time constant For example, to read in 10 characters, the total timeout for the read operation is calculated as:

Read Total timeout =readtotaltimeoutmultiplierx10+readtotaltimeoutconstant

It can be seen that the settings for interval timeouts and total timeouts are irrelevant, which makes it easy for the communication program to set various timeouts.

If all write timeout parameters are 0, write timeouts are not used. If ReadIntervalTimeout is 0, then the read interval timeout is not used. If both ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant are 0, the read total timeout is not used. If the read interval timeout is set to Maxdword and the read time factor and the read time constant are 0, the read operation returns immediately after reading the contents of the input buffer, regardless of whether the required characters are read or not.
When the serial port is read and written in overlapping ways, although ReadFile and WriteFile may return before the operation is complete, the timeout still works. In this case, the timeout is defined as the completion time of the operation, not the return time of ReadFile and WriteFile.

Sample code to configure the serial port:

1Setupcomm (HCom,1024x768,1024x768);//both the input buffer and the output buffer size are2Commtimeouts timeouts;//Set Read Timeout3timeouts.readintervaltimeout= +;4Timeouts.readtotaltimeoutmultiplier= -;5Timeouts.readtotaltimeoutconstant= the;//Set Write timeout6Timeouts.writetotaltimeoutmultiplier= -; 7Timeouts.writetotaltimeoutconstant= -; 8SetCommTimeouts (hcom,&timeouts);//set timeout DCB DCB;9Getcommstate (hcom,&DCB); TenDcb. Baudrate=9600;//baud rate is 9600 OneDcb. Bytesize=8;//each byte has 8 bits ADcb. parity=noparity;//no parity bit -Dcb. Stopbits=twostopbits;//Two stop bits -SetCommState (hcom,&DCB); thePurgeComm (hcom,purge_txclear| Purge_rxclear);//emptying buffers

Before reading and writing the serial port, also use the PurgeComm () function to empty the buffer, the function prototype:

12     //3     //4 );  

3, read and write serial port

We use ReadFile and WriteFile to read and write the serial port, the following is a declaration of two functions:

 1  bool ReadFile ( 2  HANDLE hfile,  3  lpvoid lpbuffer The address of the data store that was read in, The data that is read is stored in a memory area that is the first address of the value of the pointer,  4  DWORD nnumberofbytestoread, //  5  Lpdword Lpnumberofbytesread,//  points to a DWORD value, This value returns the number of bytes actually read in the read operation  6  lpoverlapped lpoverlapped //  7 ); 

The Declaration prototype of the write function:

12     // The handle of the serial port 3     lpcvoid lpbuffer,   //  Address of the data store written to 4     // bytes to write data 5     //  6     //  7 );  

Whether the ReadFile and WriteFile functions are synchronous or asynchronous is determined by the CreateFile function, and if the FILE_FLAG_OVERLAPPED flag is specified when the handle is called CreateFile. The operations that call ReadFile and WriteFile on the handle should be overlapping, and the read and write operations should be synchronous if no overlapping flags are specified. The synchronization or asynchrony of the ReadFile and WriteFile functions should be consistent with the CreateFile function.

You should use the Clearcommerror function to clear the error before you use the ReadFile function for read operations. The Clearcommerror function is prototyped as follows:

12     //3     //4     // 5);    

The function obtains the communication error and reports the current state of the serial port, and the function clears the serial port error flag to continue the input and output operation. The parameter Lpstat points to a COMSTAT structure that returns the serial port status information.

For example, read and write the serial code in synchronous mode:

1 //Synchronous read serial port2 Charstr[ -]; 3DWORD Wcount;//number of bytes read4BOOL Breadstat; Breadstat=readfile (HCOM,STR, -,&wcount,null); 5 if(!Breadstat)6 { 7AfxMessageBox ("Read serial failed!"); 8     returnFALSE;9 } Ten returnTRUE; One  A //Synchronous write serial port - Charlpoutbuffer[ -];  -DWORD dwbyteswrite= -;  the Comstat Comstat; - DWORD dwerrorflags; -BOOL Bwritestat; Clearcommerror (hcom,&dwerrorflags,&comstat); -Bwritestat=writefile (hcom,lpoutbuffer,dwbyteswrite,&dwbyteswrite,null);  + if(!Bwritestat) - {  +AfxMessageBox ("failed to write serial port!");  A }  atPurgeComm (HCom, purge_txabort| Purge_rxabort| purge_txclear| Purge_rxclear);

4. Close the serial port

Using the API function to close the serial port is very simple, just call CloseHandle using the handle returned by the CreateFile function as a parameter:

1 BOOL CloseHandle (2     // handle to object to close 3 );

VC + + Serial Communication programming detailed

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.