Using VC 6.0 of the three serial communication methods

Author:    Updated:2008-3-26 12:34:48
Abstract: This paper introduces the Windows platform in the realization of serial communication mechanisms, discussed under different conditions with Visual C + + design of the three serial communication program, and in light of reality and realizing the temperature monitoring data reception.

In the laboratory and industrial applications, the serial port is used computer equipment and external serial data transmission between the channels, as serial communication facilitate easy, so widely used. According to different conditions to achieve a flexible programming of serial control is what we need.

In the optical lens coating process, using SCM for multi-channel temperature data acquisition and control, collection results to enter the serial console every 10 S send a sample to the mainframe data to the host microcontroller sent to the relevant control orders, Serial data reception, processing, recording, display, real-time rendering curve. Serial communication program development environment for VC + + 6.0.

Serial communications under Windows

Under the previous DOS serial communication program different is that Windows does not promote the application directly control hardware, but by the Windows operating system to provide device drivers for data transmission. Serial Port in Win 32 as document processing, rather than directly to the port operation, serial communication, Win 32 provides the file I / O functions and communications function of the understanding of the use of these functions can be prepared in line with the needs of different communication procedures. Communications equipment associated with the structure of COMMCONFIG, COMMPROP, COMMTIMEOUTS, COMSTAT, DCB, MODEMDEVCAPS, MODEMSETTINGS a total of seven, and communications-related Windows API function total of 26 sets out in detail the reference MSDN help files. In connection with the following examples are given realization of the three serial communication methods.

Serial communication of the three methods

Method 1: Use VC + + to provide serial communication control MSComm First, in the dialog box to create communication control, if the Control toolbar lack of controls through the menu Project -> Add to Project -> Components and Control can be inserted, then the controls from the toolbox pulled dialog box. At this point, you only need to provide the care component of the Windows communications driver API function interface. In other words, only need to set and monitor MSComm control attributes and events.

ClassWizard for the creation of new communications control the definition of objects (CMSComm m_Serial), the adoption of the object attributes can be set on the serial port, MSComm control a total of 27 properties, introduced here only a few common attributes:

CommPort settings and returned to the communications port, the default for COM1.

Settings in the form of a string settings and return to the baud rate, parity, data bits, stop bits.

PortOpen communications port settings and return to the state, can be opened and closed ports.

Input from receiving buffer return and delete characters.

Output buffer to the sender wrote a string.

Input InputLen set each of the characters read the number, the default value is 0, that readers receive the full content of the buffer zone.

InBufferCount Back to the buffer zone has received to the number of characters, their home 0 receive buffer can be cleared.

InputMode definition Input attribute data acquisition method (0: Text; 1: binary mode).

RThreshold and SThreshold attribute that OnComm before the incident, receiving buffer zone or buffer can be sent to receive the number of characters.

Following is by setting control properties to initialize the serial port examples:

BOOL CSampleDlg:: PortOpen ()
(
BOOL m_Opened;
......
M_Serial.SetCommPort (2); / / designated Serial No.
M_Serial.SetSettings ( "4800, N, 8, 1") / / set communication parameters
M_Serial.SetInBufferSize (1024), / / designated to receive buffer size
M_Serial.SetInBufferCount (0) / / receive buffer empty
M_Serial.InputMode (1) / / set data acquisition methods
M_Serial.SetInputLen (0) / / set up for reading
M_Serail.SetPortOpen m_Opened = (1) / / open the designated serial
Return m_Opened;
)

Open for serial, serial communication need to consider the timing. Receive or send data in the process, may need to monitor and respond to some of the events and errors, event-driven serial port is handling the interaction of a very effective method. CommEvent OnComm events and the use of attributes capture and check communications events and the wrong values. Communications incident occurred or wrong, it would trigger OnComm, CommEvent the value of the attribute will be changed, the application checks CommEvent attribute values and corresponding response. ClassWizard used in the procedure for adding OnComm CMSComm control message processing function:

Void CSampleDlg:: OnComm ()
(
......
Switch (m_Serial.GetCommEvent ())
(
Case 2:
/ / Serial port data reception, processing;
)
)



Method 2: achieve in the single-threaded serial communication from the definition of class

Easy-to-use controls, but must get the dialog box use, and in some threads need to achieve communications applications, too, the use of controls. At this time, if the different needs can be customized according to the flexible type serial communication control will offset the shortage, the following will be in the single-threaded on how to build customized communications category.

The Communications CSimpleComm need to manually add header files and source document, and its base class for CObject broadly established the following steps:

(1) open ports, serial port access to resources handle

CreateFile communication program from the designated serial equipment and related operating properties. Return to a handle, the handle will be used for the follow-up communications operation, which runs through the entire communication process. CreateFile () function in a few noteworthy parameter settings: the serial-sharing approach should be set to 0, serial devices to be shared; building methods must be OPEN_EXISTING that the serial has been opened. DwFlagAndAttribute parameters for the serial FILE_FLAG_OVERLAPPED meaningful value is the mark indicates that the use of serial asynchronous communication model, which can carry out operations overlap; if value is NULL, compared with synchronous communication mode, synchronous mode, the application will always Flow control procedures, until the end of proceedings, if factors such as communication failures encountered, the application will lead to a permanent wait, it is generally used for asynchronous communication.

(2) serial settings

Serial open, its attributes are set to the default value, in accordance with specific needs by calling GetCommState (hComm, & dcb) read the serial device control block DCB (Device Control Block) provision, the revised through SetCommState (hComm, & dcb) its inclusion. Asynchronous read and write again to the attention of overtime control settings, the structure set up by COMMTIMEOUTS overtime, calling SetCommTimeouts (hComm, & timeouts) will be included in the results. Following is the temperature monitoring program in the initialization of the serial function:

BOOL CSimpleComm:: Open ()
(
DCB dcb;

M_hIDComDev = CreateFile ( "COM2"
GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_
NORMAL | FILE_FLAG_OVE RLAPPED, NULL);
/ / Open the serial port, asynchronous operation
If (m_hIDComDev == NULL) return (FALSE);

Dcb.DCBlength = sizeof (DCB);
GetCommState (m_hIDComDev, & dcb); / / default port
Dcb.BaudRate = CBR_4800;
Dcb.ByteSize = 8;
Dcb.Parity = NOPARITY;
Dcb.StopBits = (BYTE) ONESTOPBIT;
...)

(3) serial read and write operation

Main use ReadFile () and WriteFile () API function, if the asynchronous communication mode, in the last two function parameters at OVERLAPPED a non-null pointer structure in the reading and writing functions return values FALSE circumstances, call GetLastError () function , and the return value for ERROR_IO_PENDING that I / O operations hoisted, the operation is to continue to implement into the background. At this point, can be used WaitForSingleObject () to wait for the signal and set the end of the longest waiting time, for example as follows:

BOOL bReadStatus;
BReadStatus = ReadFile (m_hIDComDev, buffer,
DwBytesRead, & dwBytesRead, & m_OverlappedRead);
If (! BReadStatus)
(
If (GetLastError () == ERROR_IO_PENDING)
(
WaitForSingleObject (m_OverlappedRead.hEvent, 1000);
Return ((int) dwBytesRead);
)
Return (0);
)
Return ((int) dwBytesRead);

M_Serial global variables defined as a new communications category CSimpleComm the target of the members by calling the function can be realized for serial communication function. Compared with a method, the method of serial communication program gives greater flexibility to design, write and read port option of a simple query, or by setting up peripherals and the data sent the same time interval timer TimeCycle: SetTimer (1, TimeCycle, NULL), regularly read or sent.

CSampleView:: OnTimer (UINT nIDEvent)
(
Char InputData [30];
M_Serial.ReadData (InputData, 30);
/ / Data processing
)

If the data port on the response time requirements more stringent, and can be event-driven I / O read and write, Windows definition of the nine kinds of serial communication, the more commonly used are:

EV_RXCHAR: receiver to a byte, and Add input buffer.

EV_TXEMPTY: output buffer zone in the final one character sent.

EV_RXFLAG: receive incident characters (DCB structure EvtChar members) Add input buffer.

Using SetCommMask () designated useful after the incident, the application of available WaitCommEvent () to wait for the incidents.
SetCommMask (hComm, 0) would WaitCommEvent () suspension.


Thread under way more than three serial communication

Methods 1, 2 applies to single-threaded communication. In many industrial control systems, often through expansion connect multiple serial peripherals, the duplication of data sent peripherals different frequency, real-time error-free background requirements capture, acquisition, processing, recording the data port, which requires self - the definition of serial communication port surveillance category to create threads to the designated time of the incident to the relevant information and send a notification window.

The basic concept of threads can see bibliography VC + +, Windows internal control procedures in the first activities of the allocation of CPU time between the threads, Win 32 distinguish between two different types of thread, a thread is the user interface UI (User Interface Thread), which contain information or news circulating pump for the receiver to deal with the news; the other is working threads (Work Thread), which no news cycle for the implementation of the background tasks. Serial incident to monitor thread is the working thread.

Multithreading Communications in the preparation of the port configuration, and connecting parts of the same single-threaded communication in the port configuration has been completed, the most important thing is that according to the actual situation, the establishment of a multi-thread synchronization between the objects, such as lights, critical incident, the details may refer to VC + + synchronization category.

All are ready to start the work thread:

* = AfxBegin CommThread CWinThrea
Thread (CommWatchThread, / / thread function names
(LPVOID) m_pTTYInfo, / / transmission parameters
THREAD_PRIORITY_ABOVE_NORMAL, / / thread priority setting
(UINT) 0, / / size of the largest stack
(DWORD) CREATE_SUSPENDED, / / create signs
(LPSECURITY_ATTRIBUTES) NULL); / / safety signs

At the same time, events in the serial monitor thread:

If (WaitCommEvent (pTTYInfo-> idComDev, & dwEvtMask, NULL))
(
If ((dwEvtMask & pTTYInfo-> dwEvtMask) == pTTYInfo-> dwEvtMask)
(
WaitForSingleObject (pTTYInfo-> hPostEvent, 0xFFFFFFFF);
ResetEvent (pTTYInfo-> hPostEvent); / / Purchase incidents targeting non-synchronous signal -
:: PostMessage (CSampleView, ID_COM1_DATA, 0,0); / / notifications sent news
)
)

Use PostMessage () to the designated window send a notification message queue information corresponding to the need to establish information in the window and members of the mapping function, the information will be used ON_MESSAGE function names associated with members.

BEGIN_MESSAGE_MAP (CSampleView, CView)
/ / ((AFX_MSG_MAP (CSampleView)
ON_MESSAGE (ID_COM1_DATA, OnProcessCom1Data)
ON_MESSAGE (ID_COM2_DATA, OnProcessCom2Data)
.....
/ /)) AFX_MSG_MAP
END_MESSAGE_MAP ()

Then in the function of the completion of the serial data received treatment, but must ensure that the next monitoring data have to come before the middle to complete all the work. To do otherwise would result data capture errors.

Multithreading can make the realization of the port independent, accurate realization of serial communication, the serial communication with a wide range of flexibility and more strict, and made full use of CPU time. But in specific real-time monitoring system in how to coordinate multiple threads, thread between the manner in which is synchronized serial communication in a multi-threaded program difficult.

In VC + + 6.0 as a tool for achieving the three serial communication methods have their advantages and disadvantages,

According to different needs, choose the right way to reach a multiplier effect. In the temperature monitoring system, the authors used two methods in Window 98, Windows 95, run on stability, and achieved good results.
Previous:Using Visual C + + to achieve the PDF document shows
Next:Based on the Visual C + + 6.0 Programming DDL
User Reviews
Site Search
Related Articles
Recommended article
AD