General writing method of communication program

Publisher:cocolangLatest update time:2018-03-07 Source: eefocus Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

    Now most of the instruments and equipment require to be operated by the host computer software, which is convenient for debugging and operation. This involves the communication process. In the actual production of several devices, the author summarized the general writing method of the communication program, including the host computer side and the slave computer side, etc.

    1. Custom data communication protocol

    The data protocol mentioned here is the communication data packet format built on the physical layer. The so-called physical layer of communication refers to the communication methods we usually use, such as RS232, RS485, infrared, optical fiber, wireless, etc. At this level, the underlying software provides two basic operation functions: sending a byte of data and receiving a byte of data. All data protocols are built on these two operation methods.


    The data in communication is often transmitted in the form of data packets, and we call such a data packet a frame of data. Similar to the TCPIP protocol in network communication, a more reliable communication protocol often contains the following components: frame header, address information, data type, data length, data block, checksum, and frame tail.

    The frame header and frame tail are used to determine the integrity of the data packet. Usually, a fixed byte of a certain length is selected to form the frame. The requirement is that the error rate of the data packet in the entire data link is as low as possible. Reduce the matching chance of fixed byte data, that is, minimize the chance that the characteristic bytes of the frame header and frame tail can match in the entire data link. There are usually two ways to do this: one is to reduce the matching probability of the characteristic bytes. The other is to increase the length of the characteristic bytes. Usually, the first method is selected when the data in the entire data link is not random and the data is predictable. It can be avoided by manually selecting the characteristic words of the frame header and frame tail, thereby reducing the matching probability of the characteristic bytes. The second method is more general and suitable for occasions where the data is random. By increasing the length of the characteristic bytes to reduce the matching probability, although it cannot completely avoid the matching situation, it can greatly reduce the matching probability. If a matching situation is encountered, it can also be detected by the check code, so this situation is more reliable in most cases.

    Address information is mainly used in multi-machine communication, and different communication terminals are identified by different address information. In a one-to-many communication system, only the destination address information can be included. Including both the source address and the destination address is suitable for a many-to-many communication system.

    The data type, data length and data block are the main data parts. The data type can identify whether the following is a command or data. The data length is used to indicate the number of valid data.

    The checksum is used to check the integrity and correctness of the data. It is usually obtained by performing related operations on the data type, data length and data block. The simplest way is to add up the data segments, and the more complex way is to perform CRC operations on the data. You can choose according to the requirements of operation speed, fault tolerance, etc.

    2. Data transmission between the host computer and the slave computer

    The physical communication layer provides two basic operation functions. Sending a byte of data is the basis for data transmission. The transmission of a data packet is to send the left and right bytes in the data packet one by one in order. Of course, there are different ways of sending.

    In the single-chip microcomputer system, the more commonly used method is to directly call the function of sending a single byte of data through the serial port. The disadvantage of this method is that the processor needs to participate in the entire sending process. The advantage is that the data to be sent can immediately appear on the communication line and can be immediately received by the receiving end. Another method is to use the interrupt sending method. All the data to be sent is sent into a buffer, and the data in the buffer is sent out using the send interrupt. The advantage of this method is that it occupies less processor resources, but it may happen that the data to be sent cannot be sent immediately, but the delay is quite small. For the 51 series single-chip microcomputer, it is more inclined to use the direct sending method. The interrupt sending method occupies more RAM resources and does not have many advantages compared to direct sending. The following is the function of sending a single byte in the 51 series single-chip microcomputer.

    void SendByte(unsigned char ch)

    {

    SBUF = ch;

    while(IF == 0);

    IF = 0;

    }

    There are also many ways to communicate with the serial port in the host computer. This method does not refer to whether the data is buffered or not, but the different ways of operating the serial port, because the data sent on the PC will basically be buffered before being sent. For programming, there are three ways to operate the serial port. First, use the serial port communication control that comes with the Windows system. This method is relatively simple to use. It is necessary to pay attention to the blocking processing and thread mechanism when receiving. Second, use the system API to directly read the serial port data. In Windows and Linux systems, the device is virtualized as a file. You only need to use the API function provided by the system to send and read serial port data. Third, use the serial port class to operate the serial port. Here we only introduce the programming method using the serial port class in the Windows environment.

    CSERialport is a relatively easy-to-use serial port class. It provides the following serial port operation methods:

    void WriteToPort(char* string, int len);

    After the serial port is initialized successfully, call this function to send data to the serial port. In order to avoid the delay caused by the serial port buffer, the flushing mechanism of the serial port can be enabled.

    3. Data reception and protocol analysis in the lower computer

    There are also two ways for the lower computer to receive data: one is waiting for reception, and the processor keeps checking the serial port status to determine whether data has been received. The other is interrupt reception. The advantages and disadvantages of the two methods have been discussed in detail in a previous article on serial communication. The conclusion is that the interrupt reception method is better.

    The parsing process of the data packet can be set to different locations. If the protocol is relatively simple and the entire system only processes some simple commands, the parsing process of the data packet can be directly placed in the interrupt processing function. When the correct data packet is received, the corresponding flag is set, and the command is processed in the main program. If the protocol is slightly complex, a better way is to store the received data in a buffer, and the main program reads the data and then parses it. There are also two ways of cross-use. For example, in a one-to-many system, the "connect" command is first parsed in the receive interrupt. After the connection command is received, the main program enters the setup state and uses the query method to parse the rest of the protocol.

    The following is a specific example. In this system, the serial port commands are very simple. All protocols are carried out in the serial port interrupt. The format of the data packet is as follows:

    0x55, 0xAA, 0x7E, 0x12, 0xF0, 0x02, 0x23, 0x45, SUM, XOR, 0x0D

    Among them, 0x55, 0xAA, 0x7E are the frame header of the data frame, 0x0D is the frame tail, 0x12 is the destination address of the device, 0xF0 is the source address, 0x02 is the data length, followed by two data 0x23, 0x45, starting from the destination address to calculate the accumulation, XOR checksum and end at the last bit of the data.


    The purpose of protocol parsing is to first determine the integrity and correctness of the data packet, then extract the data type, data and other data, and store them for the main program to process. The code is as follows:

    if(state_machine == 0) // Protocol parsing state machine

    {

    if(rcvdat == 0x55) // Receive the first data of the frame header

    state_machine = 1;

    else

    state_machine = 0; // state machine reset

    }

    else if(state_machine == 1)

    {

    if(rcvdat == 0xAA) // Receive the second data of the frame header

    state_machine = 2;

    else

    state_machine = 0; // state machine reset

    }

    else if(state_machine == 2)

    {

    if(rcvdat == 0x7E) // Receive the third data of the frame header

    state_machine = 3;

    else

    state_machine = 0; // state machine reset

    }

    else if(state_machine == 3)

    {

    sumchkm = rcvdat; // Start calculating the accumulation and XOR checksum

    xorchkm = rcvdat;

    if(rcvdat == m_ SRC Adr) // Check if the destination address is correct

    state_machine = 4;

    else

    state_machine = 0;

    }

    else if(state_machine == 4)

    {

    sumchkm += rcvdat;

    xorchkm ^= rcvdat;

    if(rcvdat == m_DstAdr) // Check if the source address is correct

    state_machine = 5;

    else

    state_machine = 0;

    }

    else if(state_machine == 5)

    {

    lencnt = 0; // Receive data counter

    rcvcount = rcvdat; // Receive data length

    sumchkm += rcvdat;

    xorchkm ^= rcvdat;

    state_machine = 6;

    }

    else if(state _machine == 6 || state _machine == 7)

    {

    m_ucData[lencnt++] = rcvdat; // data saving

    sumchkm += rcvdat;

    xorchkm ^= rcvdat;

    if(lencnt == rcvcount) // Determine whether the data has been received

    state_machine = 8;

    else

    state_machine = 7;

    }

    else if(state_machine == 8)

    {

    if(sumchkm == rcvdat) // Check if the sum is equal

    state_machine = 9;

    else

    state_machine = 0;

    }

    else if(state_machine == 9)

    {

    if(xorchkm == rcvdat) // Check if the XOR checksum is equal

    state_machine = 10;

    else

    state_machine = 0;

    }

    else if(state_machine == 10)

    {

    if(0x0D == rcvdat) // Determine whether the end of the frame is received

    {

    retval = 0xaa; // Set the flag to indicate that a data packet has been received

    }

    state_machine = 0; // Reset state machine

    }

    In this process, a variable state_machine is used as the transition state of the protocol state machine to determine the position of the current byte in a frame of data. At the same time, the received data is automatically checked and processed during the receiving process. When the data packet is received, the check is also compared. Therefore, when the end of the frame is received, it means that a frame of data has been received and passed the check, and the key data is also saved in the buffer. The main program can parse the protocol through the flag bit of retval.

    During the receiving process, as long as the data received in any step is not the expected value, the state machine will be reset directly for judging the next frame of data. Therefore, the system rarely has state deadlock and the system is relatively stable. If the data packet is lost, the host computer can also resend the command, but the author has not encountered this situation yet.

    The process of protocol processing in the main program is similar to this. The data in the serial port buffer is continuously read in the main program loop. This data is involved in the protocol processing in the main loop. The code is exactly the same as described above.


    4. Data reception and command processing in the host computer

    The data receiving process in the upper computer can be completely consistent with that in the lower computer, but the operation methods for different serial ports are different. For blocking serial port reading functions, such as direct API operations or calling Windows serial port communication controls, it is best to start a thread specifically for monitoring serial port data reception, and send a message to the system every time a data is received. This is the processing process in the CSerialPort class that I often use. After CSerialPort opens the serial port, it starts a thread to monitor the serial port data reception, saves the received data to the buffer, and sends a message to the parent process to receive the data. The data will be sent to the parent process along with the message. Open the processing function of this message in the parent process, and after obtaining the serial port data from it, you can copy the above code and use it.


    The message numbers that CSerialPort sends to the parent class are as follows:

    #define WM_COMM_RXCHAR WM_USER+7 // A character was received and placed in the input buffer.

    Therefore, you need to manually add the response function for this message:

    afx_msg LONG OnCommunICation(WPARAM ch, LPARAM port);

    ON_MESSAGE(WM_COMM_RXCHAR, OnCommunication)

    The specific code of the response function is as follows:

    LONG CWellInfoView::OnCommunication(WPARAM ch, LPARAM port)

    {

    int retval = 0;

    rcvdat = (BYTE)ch;

    if(state_machine == 0) // Protocol parsing state machine

    {

    if(rcvdat == 0x55) // Receive the first data of the frame header

    state_machine = 1;

    else

    state_machine = 0; // state machine reset

    }

    else if(state_machine == 1)

    {

    if(rcvdat == 0xAA) // Receive the second data of the frame header

    state_machine = 2;

    else

    state_machine = 0; // state machine reset

    ......

    5. Conclusion

    The above is the basic prototype of the operation of the communication system. Although it is simple, it is feasible. The protocol in the actual communication system is more complicated than this, and involves a series of problems such as data packet response, command errors, delays, etc. On this basis, these difficulties can be overcome and a relatively stable and reliable system can be realized.


Reference address:General writing method of communication program

Previous article:Kinetis UART serial port (DMA mode)
Next article:A simpler way to download programs without powering off STC microcontrollers

Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号