VS_MFC: CSerialPort serial communication

Reference link:  
Afx global functions and MFC common data types  
CSerialport class open source address (hosted by Chinese people on github)  
CSerialPort serial port class latest revised version and source code simple analysis  
The serial port class URL provided by Remon (English)  
[MFC] Use a powerful third-party Serial port class CSerialPort


What is serial communication

The serial port is a data transmission channel between a computer and peripheral devices. It is widely used because it is very convenient for communication and can realize long-distance data transmission. In a Windows environment, the serial port is part of the system resources. If an application wants to use the serial port for communication, it must submit a resource request to the operating system (open the serial port) before using it. After the communication is completed, the resource must be released, that is, close the serial port. The most important parameters of serial communication are rate, data bits, stop bits and parity.

- Data format of serial communication

write picture description here 
One character is transmitted character by character, each character is transmitted bit by bit, and when a character is transmitted, it always starts with a "start bit" and ends with a "stop bit", and there is no fixed time interval between characters.

Each character is preceded by a start bit (low level), the character itself consists of 7 data bits, followed by a check bit (check bit can be odd check, even check or no check) Check bit), and finally a one-bit or one-half or two-bit stop bit, the stop bit is followed by an idle bit of indefinite length, and both the stop bit and the idle bit are specified as high level. In actual transmission, the signal width of each bit is related to the baud rate. The higher the baud rate, the smaller the width. Before transmission, both parties must use the same baud rate setting.

  • Even and odd parity

In standard ASCII, its most significant bit (b7) is used as a parity bit. The so-called parity check refers to a method used to check whether there is an error during the code transmission process, and is generally divided into two types: odd check and even check. Odd check regulation: the number of 1s in a byte of the correct code must be an odd number, if not, add 1 to the highest bit b7; even check regulation: the number of 1s in a byte of the correct code must be an even number , if it is not even, add 1 to the highest bit b7.

  • stop bit

Stop bits are counted by length. Serial asynchronous communication starts from timing and takes unit time as an interval (one unit time is the reciprocal of the baud rate), accepts the specified data bits and parity bits in turn, and assembles them into parallel bytes of a character; A stop bit "1" of the specified length was received. Therefore, the stop bits are all "1", and 1.5 is its length, that is, the high level of the stop bit is maintained for 1.5 units of time. Generally speaking, the stop bit has three lengths of 1, 1.5, and 2 units of time.

  • baud rate

The baud rate is the number of bits of data transmitted per second. The unit of baud rate is the number of bits per second (bps), and the commonly used units are: Kbps, the number of kilobits per second, and Mbps, the number of megabits per second. The typical transmission baud rate of serial port is 600bps, 1200bps, 2400bps, 4800bps, 9600bps, 19200bps, 38400bps. 
When the PLC/PC communicates with the weighing instrument, the most commonly used baud rates are 9600bps and 19200bps. When the PLC/PC or instrument communicates with the large screen, the most commonly used baud rate is 600bps.

- Communication method of serial communication

Simplex mode (Simplex Communication) data transmission is unidirectional. Among the two communication parties, one is fixed as the sender, and the other is fixed as the receiver. Information can only travel in one direction, using a single transmission line.

Half-duplex mode (HalfDuplex) communication uses the same transmission line, which can both send and receive data, but cannot send and receive at the same time. Data transmission allows data to be transmitted in both directions, however, only one of them can send data and the other can receive data at any one time. Therefore, the half-duplex mode can use either one data line or two data lines. In half-duplex communication, each end needs to have an electronic switch for sending and receiving switching, which determines which direction data is transmitted through switching. Because of switching, time delay will occur, and information transmission efficiency is lower.

Full-duplex mode (FullDuplex) communication allows data to be transmitted in both directions simultaneously. Therefore, full-duplex communication is a combination of two simplex communication methods, which requires that both the sending device and the receiving device have independent receiving and sending capabilities. In full duplex mode, each end has a transmitter and a receiver, there are two transmission lines, and the information transmission efficiency is high.

Obviously, when other parameters are the same, full-duplex transmission is faster and more efficient than half-duplex.

  • Typical serial communication standard

①EIA RS232 (usually referred to as "RS232"): formulated by the Electronic Industries Association (EIA) in 1962. 
②EIA RS485 (usually referred to as "RS485"): formulated by the Electronic Industries Association (EIA) in 1983.

The serial port used in the project is an RS232 serial port.

RS232 serial port

RS232 is the most widely used serial interface in the computer and communication industry. It works in full duplex mode and requires three wires: ground, transmit and receive. RS232 can only realize point-to-point communication.

Definition of RS232 serial port interface: 
RXD: receive data; 
TXD: send data; 
GND/SG: signal ground. 
Definition of computer DB9 pin interface: 
Disadvantages of RS232 serial port Computer DB9 pin interface is a common RS232 serial port (as shown in the figure), and its pins are defined as follows: Pin 
2: RXD (receive data) 
Pin 3: TXD (transmit data) 
Pin 5 : SG or GND (signal ground) 
other pins: we do not use 
write picture description here

Disadvantages of RS232 serial port: 
The interface signal level value is high, and the interface circuit chip is easily damaged. 
● Low transmission rate, the highest baud rate is 19200bps. 
● Poor anti-interference ability. 
● The transmission distance is limited, generally within 15m. 
● Only point-to-point communication is possible.

- Realization of serial communication under VS2013

Under VS2013, there are several ways to realize serial communication:

1) Use the API communication function; 
2) Use the serial communication control MScomm; 
3) Use the serial port communication class SerialPort provided by Microsoft; 
4) Use the open source CSerialPort class written by Remon Spekreijse; the 
project mainly uses the CSerialPort class for serial communication programming, and then Next, we will introduce the realization of serial communication with CSerialPort.

A brief description of the CSerialPort class

The CSerialPort class is an open source serial port class written by a man named Remon Spekreijse, which is very powerful.

CSerialPort Workflow

First set the serial port parameters, and then start the serial port detection worker thread. After the serial port detection worker thread detects the data received by the serial port, flow control events or other serial port events, it will notify the main program in the form of a message, and activate the message processing function to perform data processing. , this is for receiving data, and sending data can be sent directly to the serial port.

Messages defined by the CSerialPort class

The message is as follows:

message name message number Function Description
WM_COMM_BREAK_DETECTED WM_USER+1 Input interruption detected
WM_COMM_CTS_DETECTED WM_USER+2 CTS (clear to send) signal state change detected
WM_COMM_DSR_DETECTED WM_USER+3 DSR (Data Device Ready) signal state change detected
WM_COMM_ERR_DETECTED WM_USER+4 A line state error occurred (including CE_FRAMECE_OVERRUN, and CE_RXPARITY)
WM_COMM_RING_DETECTED WM_USER+5 Ring indicator detected
WM_COMM_RLSD_DETECTED WM_USER+6 RLSD (Receive Line Signal) state change detected
WM_COMM_RXCHAR WM_USER+7 A character was received and placed in the accept buffer
WM_COMM_RXFLAG_DETECTED WM_USER+8 A character received (the character has been placed in the accept buffer) event detected
WM_COMM_TXEMPTY_DETECTED WM_USER+9 It is detected that the last character of the send buffer has been sent

port initialization

First, set several main parameters: 
(1) BaudRate (baud rate) The baud rate is the rate of the analog line signal, which is measured by the number of oscillations of the waveform per second. The baud rate mainly has the following frequencies: 2400, 4800, 9600, 14400. 
(2) PortName PortName is the serial port name used by the serial port device. When designing the serial port communication program, the serial port name must be found, otherwise, the connection with the serial port device cannot be established for communication. 
(3) ReceivedBytesThreshold This parameter is mainly used to trigger the data receiving event DataReceived, which is triggered when the amount of data in the input buffer reaches the set value, otherwise it keeps waiting.

These settings are based on the specific serial device used, this article is set to 9600, com1, 1, 2048/4096. After the parameters are set, the serial port open function, SerialPort1.InitPort () is called.

Serial read and write operations

(1) Initialize the serial port 
process: check parameters -> detect thread -> create event (monitor thread) -> open port -> set asynchronous IO structure parameters. 
(2) The control of the monitoring thread 
is the thread control, which mainly includes opening the thread, resetting and stopping. 
(3) Monitoring thread 
We hand over all the operations of reading and writing the serial port to the monitoring thread. Now let’s take a brief look at the general process of the monitoring thread: 
check the serial port –> enter the loop {WaitCommEvent (non-blocking query) ask for the event –> if an event comes –> to the corresponding processing (close\read\write)} 
(4) read data operation 
Reading data is an asynchronous operation. When data is sent, the read event m_ov.hEvent will be triggered. After the monitoring thread captures the event, it will Knowing that it is a read event, enter the relevant read processing, where the function ReceiveChar is called, and the ReadFile function is called in ReceiveChar to read the serial port data into the Buffer buffer. 
(5) The operation of writing data is 
also operated by the monitoring thread, but the trigger event is handed over to the main thread to trigger. The function is WriteToPort(), which writes the data into the buffer, and then the function WriteChar() called by the thread sends the data in the buffer. The data is written to the serial port, during which WriteFile() is called.

close serial port

After using the serial port, close the serial port, the function is: ClosePort().

Serial communication example analysis

The project is based on the CSerialPort class for serial communication to realize the communication between the lower computer PLC and the upper computer PC. 
1) Design idea 
In the project, the communication between the upper and lower computers is mainly the angle value of the angle sensor, so the following will be analyzed by angle transmission. 
2) Key code analysis  ①Data
reading 
When data is sent, the read event m_ov.hEvent is triggered, and after the WM_COMM_RXCHAR event trigger condition defined by the CserialPort class is met, a custom message mapping macro ON_MESSAGE in MFC is triggered. The function OnComm() reads buffer data.

ON_MESSAGE(WM_COMM_RXCHAR, OnComm)
LONG CSerial_classDlg::OnComm(WPARAM ch, LPARAM port)
{
    ……
    m_recv = ch; 
    ……
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

②Data writing 
and writing data are relatively simple, and there is no need to monitor event operations. After preparing the required data, directly call the function WriteToPort()

void CSerial_classDlg::OnSend()
{
    ……
    m_SerialPort.WriteToPort(buf);       //发送数据
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325984873&siteId=291194637