In-depth analysis of Visual C ++ Serial Communication Programming

Source: Internet
Author: User

Different methods can be used to design asynchronous serial communication programs in windows using Visual C ++. One method can use the serial port API functions provided by windows; the other method can directly use the ActiveX control MSCOMM. OCX provided by Microsoft. Using the MSCOMM. OCX control for serial port programming is relatively simple. As long as you set and operate the properties, events, and methods of the control, you can complete the simple serial communication function. The direct use of the serial port API functions provided by windows is relatively flexible. During the experiment, you can program either of them according to your own situation. The following describes how to program the serial port API functions provided by windows.

In windows, serial port and other communication devices are processed as files. The functions used to open, close, send, and receive a serial port are the same as those used in the operation file. In general, asynchronous serial communication program design using Visual C ++ can be divided into four major stages, they are the opening stage, reading the status value and setting stage, sending and receiving stage of the serial data, and closing stage of the serial port.

(1) Open a serial port
Before you perform all operations on a serial port, open it first. You can use the CreateFile function to open a serial port. The CreateFile function returns a handle for subsequent operations related to the serial port. Similar to file operations, when using CreateFile to open a serial port, you can also specify the serial port as "Read access permission", "write access permission", or "read/write access permission ".Copy codeThe Code is as follows: HANDLE CreateFile (
Lptstr lpFileName
DWORD dwDesiredAccess
DWORD dwSharedMode
LPSECURITY_ATTRIBUTES lpSecurityAttributes
DWORD dwCreationDisposition
DWORD dwFlagsAndAttributes
HANDLE hTemplateFile
);

When the call is successful, CreateFile returns the handle to open the file, which will be used in subsequent call functions related to the serial port. If the call fails, CreateFile returns INVALID_HANDLE_VALUE.
(2) reading the status of the serial port and setting properties
Once the serial port is enabled, you can set the attributes of the serial port. Because the attributes of the serial port are very complex, it is usually used to read the current status value of the serial port, and then modify it on this basis.
Obtains the current status of a serial port.Copy codeThe Code is as follows: BOOL GetCommState (
HANDLE hFile
LPDCB lpDCB
);

The first hFile parameter of the GetCommState function is the handle returned by the CreateFile function pointing to the opened serial port. The second parameter points to the device control block DCB. DCB is a very important data structure. Almost all the serial port attributes and statuses are stored in the member variables of this structure.
Set the serial port
In windows, the SetCommState function is used to modify the current parameter configuration of a serial port. The SetCommState function declaration is as follows:Copy codeThe Code is as follows: BOOL SetCommState (
HANDLE hFile
LPDCB lpDCB
);

The first hFile parameter of the GetCommState function is the handle returned by the CreateFile function pointing to the opened serial port. The second parameter points to the device control block DCB. If the function call is successful, the return value is not 0. If the function call fails, the return value is 0. When the application only needs to modify some configuration values of the serial port, you can use the GetCommState function to obtain the current DCB structure, change the parameters, and then call the SetCommState function to set the modified DCB to configure the serial port.
Allocate the receiving and sending buffer for the serial port
When a serial port is opened, a sending buffer and a receiving buffer can be allocated to the serial port. The SetupComm function can be used to configure the sending and receiving buffers of the serial port. If SetupComm is not called, The system allocates the default sending and receiving buffers for the serial port. However, to ensure that the buffer size is consistent with the actual needs, it is best to call this function for setting. The following is a prototype of the SetupComm function:Copy codeThe Code is as follows: BOOL SetupComm (
HANDLE hFile
DWORD dwInQueue
DWORD dwOutQueue
);

The hFile function returns the handle pointing to the opened serial port. The dwInQueue and dwOutQueue parameters respectively specify the size of the receiving buffer and sending buffer recommended by the application.
Clear the receiving and sending Buffer
Before all the data sending and receiving operations on the serial port, it is best to use the PurgeComm function to clear the data in the sending and receiving buffers of the serial port. The PurgeComm function is prototype as follows:Copy codeThe Code is as follows: BOOL PurgeComm (
HANDLE hFile
DWORD dwFlages
);

The hFile parameter is the handle that is returned by the CreateFile function pointing to the opened serial port. The dwFlags parameter indicates the action to be executed. If dwFlags is PURGE_TXCLEAR, the system is notified to clear the sending buffer; If dwFlags is PURGE_RXCLEAR, the system is notified to clear the receiving buffer; if you need to clear all the sending and receiving buffers, you can set dwFlags to PURGE_TXCLEAR | PURGE_RXCLEAR. If the PurgeComm function is successfully called, the returned value is not 0. If the function fails to be called, the returned value is 0.
(3) sending and receiving of Serial Data
Similar to common file operations, when operating a serial port, the ReadFile function is usually used to read the data received by the serial port, and WriteFile is used to write the data to be sent as a serial port.
Receive serial data
The ReadFile function can be used to read data received by the serial port. The ReadFile function is prototype as follows:Copy codeThe Code is as follows: BOOL ReadFile (
HANDLE hFile
LPVIOD lpBuffer
DWORD nNumberOfBytesToRead
LPDWORD lpNumberOfBytesRead
LPOVERLAPPED lpOverlapped
);

The hFile parameter points to the opened serial port handle; The lpBuffer points to a read data buffer; The nNumberOfBytesToRead specifies the number of bytes to be read from the serial device; and The lpNumberOfBytesRead indicates the number of bytes actually read from the serial port; lpOverlapped points to an OVERLAPPED structure variable, which contains a synchronization event.

If the call is successful, ReadFile returns a non-0 value; otherwise, the returned value is 0. However, for serial ports that receive operations in the background, the return value of 0 does not necessarily indicate that the function call fails. You can call the GetLastError function to obtain further information. If the returned value of GetLastError is ERROR_IO_PENDING, it means that the operation to read the serial port is still in the background waiting state, rather than a real error.
Transmission of Serial Data
The WriteFile function can be used to write data to the serial port. The WriteFile function is prototype as follows:Copy codeThe Code is as follows: BOOL WriteFile (
HANDLE hFile
LPVIOD lpBuffer
DWORD nNumberOfBytesToWrite
LPDWORD lpNumberOfBytesWritten
LPOVERLAPPED lpOverlapped
);

The hFile parameter points to the opened serial port handle; lpBuffer points to a sending data buffer; nNumberOfBytesToRead specifies the number of bytes to be sent from the serial device; lpNumberOfBytesRead indicates the number of bytes actually sent from the serial port; lpOverlapped points to an OVERLAPPED structure variable, which contains a synchronization event.

Generally, if the call is successful, WriteFile returns a non-0 value; otherwise, the return value is 0. However, if the returned value is 0 for the serial port sending operation in the background, the function call fails. You can call the GetLastError function to obtain further information. If the returned value of GetLastError is ERROR_IO_PENDING, it indicates that the operation to write data to the serial port is still in the background waiting state, rather than a real error.
(4) Close the serial port
Usually close a serial port after it is used up. If you forget to close it, the serial port will always be open, and other applications will not be able to open or use it.
You can use CloseHandle to disable the serial port. The function prototype is as follows:
Copy codeThe Code is as follows: BOOL CloseHandle (
HANDLE hObject
);

The CloseHandle function is very simple, and the hObject is the handle to open the serial port. If the function is successfully called, the return value is not 0; otherwise, the return value is 0.

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.