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. 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(TI == 0); TI = 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_SrcAdr) // 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 it involves a series of problems such as data packet response, command errors, delays, etc. On this basis, these difficulties can be overcome and a more stable and reliable system can be realized.
Previous article:MCU implements multithreading
Next article:MSP430 flash operation
Recommended ReadingLatest update time:2024-11-16 20:27
Design of 12864 LCD animation effect based on single chip microcomputer
The design demonstrates the effect: the upper half of the screen displays static Chinese characters (* * *I believe you will succeed!), and the lower half of the screen displays animation effects (a hammer hitting a nail, and a looping effect of the hammer falling and the nail being driven in). The c
[Microcontroller]
STM8 series MCU multiplexing pin programming program precautions
When I was burning a program for a recent project, the program did not match the program's function when it was successfully burned and tested. I spent a lot of time looking for the reason and finally figured it out. The program used the pin multiplexing function. But I did not configure it during debugging, so the fu
[Microcontroller]
MCU interface principle circuit diagram
The SPI interface is a synchronous serial data transmission between the CPU and peripheral low-speed devices. Under the shift pulse of the master device, the data is transmitted bit by bit, with the high bit first and the low bit last. It is full-duplex communication. The data transmission speed is generally faster tha
[Microcontroller]
Very detailed single chip traffic light control program
Use the timer to count time, the annotations are very detailed, and you can change the timing time yourself. The microcontroller source program is as follows: #include "reg52.h" #define GPIO_TRAFFIC P2 #define GPIO_DIG P0 typedef unsigned char u8; typedef unsigned int u16; //3-8 decoder pin definition sbit LSA = P
[Microcontroller]
AVR MCU Atmega128 External RAM
Since the AVR series of microcontrollers use unified addressing for internal and external RAM, ATmega128 has 4k+256B of continuous internal storage space including register files (general working registers), I/O registers, extended I/O registers and internal SRAM when working in non-ATmega 103 mode. Therefore, w
[Microcontroller]
Programming Design of ADC of PIC Microcontroller
#include __CONFIG(0X1F71); #define uchar unsigned char #define uint unsigned int const fly Tab[]= {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; const fly Tab1[]= {0xbf, 0x86, 0xdb, 0xcf, 0xe6, 0xed, 0xfd, 0x87, 0xff, 0xef}; //Code with decimal point void DisPlay(fly date1、fly date2、fly date3、fly date4); void
[Microcontroller]
Application of IDT7132 Dual-Port RAM in Single-Chip Microcomputer System
1. Introduction to IDT7132 IDT7132 is a high-speed 2K×16bit dual-port static RAM with an on-chip bus arbitration circuit. It has two sets of data buses and address buses, and the two sets of buses can access different memory units at the same time. When the two sets of address buses are exactly the same, the on-chip b
[Microcontroller]
Infineon Technologies and Magneti Marelli Collaborate to Drive Regional Control Unit Innovation with AURIX™ TC4x MCU Family
On November 8, Infineon Technologies AG and Marelli, a supplier of mobility technology for the automotive industry, collaborated to develop advanced E/E architecture solutions. The collaboration combines the automotive expertise of the two companies to develop innovative regional control units (ZCUs) using Infineon'
[Automotive Electronics]
- Popular Resources
- Popular amplifiers
- Wireless Sensor Network Technology and Applications (Edited by Mou Si, Yin Hong, and Su Xing)
- Modern Electronic Technology Training Course (Edited by Yao Youfeng)
- Modern arc welding power supply and its control
- Small AC Servo Motor Control Circuit Design (by Masaru Ishijima; translated by Xue Liang and Zhu Jianjun, by Masaru Ishijima, Xue Liang, and Zhu Jianjun)
Recommended Content
Latest Microcontroller Articles
He Limin Column
Microcontroller and Embedded Systems Bible
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
MoreSelected Circuit Diagrams
MorePopular Articles
- Innolux's intelligent steer-by-wire solution makes cars smarter and safer
- 8051 MCU - Parity Check
- How to efficiently balance the sensitivity of tactile sensing interfaces
- What should I do if the servo motor shakes? What causes the servo motor to shake quickly?
- 【Brushless Motor】Analysis of three-phase BLDC motor and sharing of two popular development boards
- Midea Industrial Technology's subsidiaries Clou Electronics and Hekang New Energy jointly appeared at the Munich Battery Energy Storage Exhibition and Solar Energy Exhibition
- Guoxin Sichen | Application of ferroelectric memory PB85RS2MC in power battery management, with a capacity of 2M
- Analysis of common faults of frequency converter
- In a head-on competition with Qualcomm, what kind of cockpit products has Intel come up with?
- Dalian Rongke's all-vanadium liquid flow battery energy storage equipment industrialization project has entered the sprint stage before production
MoreDaily News
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
Guess you like
- How to measure current ranging from 1uA to 1.5A
- Analysis and application of four common constant current source circuits
- To prevent smog, don’t use this weird “Japanese portable air purifier”!
- 【Featured Q&A】Battery protection and fuel gauge design
- First transceiver to support all open source smart home protocols simultaneously
- Please recommend a single op amp to implement a second-order or higher-order high-gain (32dB) active low-pass filter solution
- RSL10 Family Portrait
- Ways to reduce belly fat
- The list of components for the 2021 National Electronic Design Competition has been released. What do you think?
- Does anyone have a demo of people counting in AWR1642?