Design and Implementation of Modbus Communication in a Distributed Monitoring System Based on VB
2026-04-06 04:47:46··#1
Abstract: In industrial automation monitoring systems, to achieve real-time control and management through communication between the host computer and intelligent instruments, this paper, based on a detailed analysis of the Modbus RTU protocol and its communication principles, and combined with an application example, presents a programming method for serial communication between a computer and intelligent instruments using the MSComm communication control and Timer control in the VB 6.0 programming environment. A low-cost distributed monitoring system was established. This system is simple, practical, and has good compatibility and portability. It provides valuable reference for the communication implementation of similar control systems composed of other types of intelligent instruments and host computers. It has been successfully applied in a petrochemical enterprise, effectively improving the level of intelligent control and the enterprise's production efficiency. Keywords: smart instrument; Modbus protocol; VB 6.0; distributed monitoring system; serial communication[b][align=center]Design and realization of Modbus Communication in the Distributed Monitoring System Based on VB SHI Fei, CHEN Xing[/align][/b] Abstract: In the field of industrial automation control system, in order to realize real-time control and management by communication of computer and intelligent instrument, on the basis of the analysis of Modbus-RTU protocol and the communication principle, This paper gives a method which uses the component MSComm and Timer provided by VB. This method establishes a low cost distributed monitoring system by integrating an application. This system is easy to use and good for compatibility and portability, also have some value on the communication realization in the systems which are controlled by intelligent instrument and host computer. Moreover, it has been used in petrochemical enterprise successfully and improved the level of intelligent control and the production efficiency of the enterprise effectively. Key Words: intelligent distributed instrument; Modbus protocol; VB 6.0; monitoring system; serial communication 1 Introduction Distributed monitoring systems (DMS) have been widely used in the industrial field. For small and medium-sized equipment, many enterprises often develop their own or participate in the development of their own monitoring systems due to considerations of hardware and software investment profit margin and performance-price ratio. Distributed monitoring systems are based on microcomputers and use data communication to connect microcomputers together to achieve data sharing, thereby enabling centralized monitoring and decentralized control of industrial processes [1]. The example in this paper is a low-voltage power distribution monitoring system. With the advent of the era of automated large-scale production, dozens of motors often operate simultaneously on the production site. It is often necessary to centrally monitor the operating parameters of these motors so that operators can promptly detect and handle faults. The solution of computer + intelligent instrument is adopted, with the upper computer collecting data from the lower computer in a round-robin manner at regular intervals. The host computer and slave computer communicate via an RS485 bus. Field intelligent Modbus instruments are connected to the RS485 bus. The host computer is connected to the RS485 bus via an RS232/485 converter. Using VB programming language, the system communicates with the intelligent instruments via serial port using the Modbus protocol, forming a small distributed monitoring system while controlling costs. 2. Monitoring System Overview The system adopts a master-slave point-to-point communication method, consisting of field intelligent instruments and one PC. The field intelligent instruments are DYZB-101A low-voltage intelligent integrated protectors manufactured by Tianjin Dongtai Technology Development Co., Ltd. Since the intelligent electronic devices in this system communicate via the RS485 bus, shielded twisted-pair cable with a characteristic impedance of 120Ω is used for connection. PCs generally do not have RS485 interfaces, but they all have RS232 serial interfaces. Therefore, an RS232/485 converter is used to directly convert the RS232 serial interface to an RS485 interface, which is then connected to the intelligent instruments via the RS485 bus. In serial communication, the design is mainly based on the MSComm and Timer controls under the VB development platform. Among them, the intelligent instrument performs online detection of the power system being detected, and detects the current, voltage, apparent power, number of starts, running time, frequency and other status information of the power grid. The PC can realize data reading, diagnosis, testing and parameter updating of the instrument through the network, and easily realize telemetry, telesignal and remote control. [align=center] Fig.1 The structure of monitoring system[/align] 3 Introduction to Modbus Communication Protocol The Modbus protocol is a communication protocol developed and promoted by MODICON, and has become a standard communication protocol widely used in industrial automation controllers. Through this protocol, control devices produced by different manufacturers can be interconnected in industrial networks, thereby realizing distributed control[2]. The Modbus protocol adopts a master-slave working mode, allowing one master to communicate with multiple slaves. The address of each slave is set by the user, and the address range is 1-255. The communication adopts a command/response mode, and each command frame corresponds to a response frame. The command frame is sent by the master, and all slaves will receive the message, but only the addressed slave will respond to the corresponding command and return the corresponding response frame. Figure 2 shows a complete master-slave query-response cycle. [align=center] Figure 2 The periodic table of master-slave query-response[/align] 3.1 Modbus Protocol Communication Modes The Modbus communication protocol has two transmission modes: RTU mode and ASCII mode, as shown below: ASCII Mode: When the controller is set to communicate in ASCII (American Standard Code for Information Interchange) mode on the Modbus network, each 8-bit byte in the message is sent as two ASCII characters. The main advantage of this mode is that the character transmission interval can reach 1 second without error. RTU Mode: When the controller is set to communicate in RTU (Remote Terminal Unit) mode on the Modbus network, each 8-bit byte in the message contains two 4-bit hexadecimal characters. The main advantage of this mode is that, compared to ASCII mode, RTU mode requires fewer bits to express the same information and has a larger data throughput at the same communication rate. Therefore, under normal circumstances, industrial intelligent instruments and meters generally adopt the Modbus protocol in RTU mode. This paper adopts the Modbus RTU mode. 3.2 Modbus RTU message frame format When using RTU mode, message transmission must begin with a pause interval of at least 3.5 character time (as shown in T1-T2-T3-T4 in Table 1). The first field transmitted is the device address. The transmittable characters are hexadecimal 0-9, AF. The network device continuously detects the network bus, and when the first field (address field) is received, each device decodes it to determine whether it is sent to itself. After the last transmitted character, a pause of at least 3.5 character time marks the end of the message. A new message can begin after this pause [3]. The entire message frame must be transmitted as a continuous stream. If there is a pause of more than 3.5 character time before the frame is completed, the receiving device will refresh the incomplete message and assume that the next byte is the address field of a new message. Similarly, if a new message continues from the previous message within a time of less than 3.5 characters, the receiving device will consider it a continuation of the previous message. This will result in an error because the value of the final CRC field cannot be correct. A typical message structure for RTU mode is shown in Table 1. Table 1 Message frame structure of RTU mode Tab.1 The message frame structure of RTU mode 3.3 Modbus basic rules (1) All RS485 communication loops should follow the master/slave mode, in which data can be transmitted between a master (such as a PC) and multiple slaves (such as DYZB-101A), and the number of slaves should be limited to 32. (2) The master initializes and controls all information transmitted on the RS485 communication loop. (3) No communication can start from a slave. (4) All communication on the RS485 loop is transmitted in the form of "information frames". (5) If the master or slave receives an information frame containing an unknown command, it will not respond. The host uses an active communication method. After communication begins, the host sequentially queries each slave device and waits for their response. After the host sends a query code, it must receive a response from the corresponding slave device within a certain period. When a communication command is sent to the instrument, the device matching the corresponding address code receives the command, reads the information, and if there are no errors, executes the corresponding task and then returns the execution result to the host. The returned information includes the address code, the function code of the executed action, the data after the action, and the error check code (CRC or LRC). If an error occurs, no information is sent. If the host does not receive any valid response from the corresponding slave device within the specified reception time, it can be considered that the slave device has a communication failure, and the query will continue from the next slave device. 4. Host Communication Software Design The DYZB-101A low-voltage intelligent integrated protector is suitable for AC 400V low-voltage power systems and serves as a protection and detection device for low-voltage motors. The data information in this intelligent instrument is mainly divided into dynamic information, query information, and control information. Dynamic information includes current, voltage, power, etc.; query information includes start count, running time, switch status, alarm, etc.; control information includes time synchronization, start, setting parameters, etc. When the host computer monitoring system acquires various information from the smart meter, it mainly adopts a polling method. Since different data information has different requirements for real-time performance, the host computer can perform periodic and non-periodic polling for various data information. The periodic polling can be set according to different polling cycles as needed. This article will take the dynamic information with high real-time requirements in the smart meter as an example to discuss the implementation of the host computer communication software [4]. 4.1 MSComm control and serial communication RS232/485 converter convert RS232 signal into RS485 signal for transmission. For the host, the communication software is to program the RS232 serial communication port. The host communication software is programmed using VB 6.0 in the Windows environment. The Windows operating system implements many complex tasks related to serial communication at the underlying level. It automatically puts all received characters into the receiving buffer, and all sent characters also enter the sending buffer. The program can read the data in the receiving buffer or send data to the sending buffer. VB6.0 is a visual programming tool developed by Microsoft, which has the characteristics of user-friendly interface, convenient programming, and simple operation. VB6.0 has a very perfect interface with the Windows system, and there are many built-in and plug-in controls that can be used to design the system. At the same time, VB6.0 also provides a very convenient communication control, MSComm. The application embeds the MSComm control and uses the event-driven or polling method provided by the MSComm control to manage serial communication [5, 6]. The event-driven method is rarely used when writing RS485 network communication programs, and the polling method is used more often. The method used in this program simplifies the commonly used polling method, without checking the CommEvent property value, saving program running time. 4.2 Programming Points 4.2.1 Implementation of Verification When the host sends a query command or receives the slave's response data, the calculation of the check code is implemented by calling the function fun_SerialCRC(). The function fun_SerialCRC() is placed in the program module. There are two methods for software implementation of CRC check: one is the calculation method; the other is the lookup table method. The calculation method is designed based on the generation principle of the CRC check code. Its advantages are: less module code, flexible modification, and good portability. Its disadvantage is: large amount of calculation. The advantages and disadvantages of the lookup table method are exactly the opposite of the calculation method. Because the CRC value of the polynomial factor in the fixed-byte CRC check calculation is fixed, the lookup table method simplifies the calculation process, saves response time, and improves communication efficiency. This paper uses the lookup table method, and the program flowchart is shown in Figure 3. [align=center] Figure 3 CRC16 table lookup implementation flowchart[/align] 4.2.2 Implementing periodic round-robin transmission To ensure that the host continuously sends query commands to each slave, the program uses a timer control Timer1, setting the interval property of the Timer control to 100ms. During the Timer event process, a subroutine SendPackage() is written to send query information from the host to a slave. This subroutine is called every 100ms, and the host sends a command to a slave. If there are ten slaves, querying one slave every 100ms will achieve round-robin transmission of ten slaves in 1 second. If the master is querying the same data information from all slaves, the command content of the query information frame is exactly the same, except that the slave address codes are different; their formats are basically the same. The flowchart of the command sending subroutine is shown in Figure 4. [align=center] Figure 4 The subroutine flowchart of sending command[/align] 4.2.3 Implementing the 50ms time limit During the command sending process, the program uses the Timer1 control to time the process. After an interruption, the master performs a polling query on each slave by calling the information sending sub-function. In the sub-function, the program uses the Output property to send the query command. Afterward, instead of checking the CommEvent property value, it starts another timer control, Timer2 (with the interval property set to 10ms), and directly uses the Input property to read the string from the receiving buffer. It reads every 10ms, and continuously receives the slave response strings until the maximum time limit (50ms) is reached. This timer event is the core of the program. It not only implements the 50ms receiving time limit, but also performs validity judgment and response on the received response data frame. The flowchart of this program segment is shown in Figure 5. [align=center]Figure 5. The event process flowchart of Timer2[/align] In the figure, REVOK—processes the event represented by mbEvent; mbEvent=0—normal reception and data parsing; mbEvent=1—address error; mbEvent=2—function code error; mbEvent=3—CRC16 check error; i—loop variable. 4.2.4 Implementation of Circular Reception Using Secure Arrays When the host receives response data from the slave, Timer2 is started to read the data in the input buffer every 10ms until the maximum time limit (50ms), thus realizing the circular reception of data in the input buffer. According to the data information returned by the slave, the host parses the received data and performs necessary processing. Generally, the data sent from the slave has a certain frame length, especially for some fixed smart meters. Therefore, the best method is to allocate two arrays in the host program according to the frame length of the communication return. One array serves as a security array, dynamically configured to continuously receive data from the serial port buffer; the other array acts as a receive array, with a length equal to the length of the transmitted data frame, used to copy and parse data from the security array. This improves the overall system's fault tolerance. The specific code (written in the timer event) is as follows: Dim inputbuf(14) As Byte 'Receive array Dim inputsafebuf() As Byte 'Safe array Dim a As Integer Dim index As Integer a = 0 …… Private Sub Timer2_Timer() Inputsafebuf = MSComm1.Input 'Put the data in the input buffer into the safe array For index = LBound(inputsafebuf) To UBound(inputsafebuf) inputbuf(index + a) = inputsafebuf(index) Next index 'Put the data in the safe array into the receive array a = UBound(inputsafebuf) + a + 1 'Loop variable, to achieve loop reception…… End Sub The inputbuf() in the code is the receive array, while inputsafebuf() is a separately allocated safe array. 4.3 Form Load Event Procedure The form load event (Form_Load) is called at the beginning of the program and is responsible for setting the communication port parameters and starting the timer Timer1. The main program code is as follows: Pravite Form_Load() MSComm.CommPort = 1 'Set the serial port to be used. Of course, you can flexibly set the input method here. Temporarily set port 1. MSComm.Settings = “9600, n, 8, 1” 'Set the baud rate and parity mode for transmission. MSComm.InputLen = 0 'Read all the required data at once. MSComm.InputMode = comInputModeBinary 'Set to binary data stream mode... MSComm1.Portopen = True 'Open the communication serial port. Timer1.Interval = 100 'Set the timer 1 timer value to 100ms. Timer1.Enable = True 'Start timer 1. Timer2.Interval = 10 'Set the timer 2 timer value to 10ms. Timer2.Enable = False 'Turn off timer 2. End Sub 4.4 Timer1 Event Procedure This event will be called once every time an attribute value is set (previously set to 100ms), completing the periodic polling communication between the master and slave. The main program code is as follows: Dim j As Integer Dim n As Integer j = 0 Pravite Timer1_Timer() j = j + 1 n = j If j >= 10 Then j = 0 'Periodic polling SendPackage n 'Call the subroutine for communication with slave device n End Sub 5 Conclusion In this monitoring system, 10 low-voltage intelligent integrated protectors are connected to the RS485 bus. The selected transmission baud rate is 9600bps. The dynamic information data in the protectors can be updated every 1 second on the PC. For other data information in the protectors, the maximum number of data frames sent and received is no more than 60 bytes. Therefore, the communication software can fully meet the stability, reliability, and accuracy requirements during transmission. However, in actual communication, the transmission baud rate and the length of the polling cycle can be adjusted according to the specific conditions of the industrial site. The communication software designed in this paper has been applied to a low-voltage power distribution monitoring system. Practice has proven that the system can operate normally, with stable and reliable communication between the host computer and the slave computer. The software is easy to use and achieves intelligent control of the DYZB-101A integrated protector, effectively reducing the failure rate in industrial settings. This communication protocol and software also have a certain degree of universality, providing a simple and practical communication solution for factories, power plants, and industrial monitoring systems. References [1] Fan Yizhi. Visual Basic and Distributed Monitoring System [M]. Beijing: Tsinghua University Press, 2002 [2] Ma Hua, Zhang Guoxun. Application of Modbus Communication Protocol in Liquid Level Monitoring System [J]. Journal of Xingtai Vocational and Technical College, 2004, 21(3): 36-38 [3] Li Xidong, Liu Tao, Liu Gang. Application of Modbus-RTU Serial Communication Protocol in Industrial Field [J]. Automation Technology and Application, 2005, 24(7): 37-40 [4] DYZB-101A Low-Voltage Intelligent Integrated Protector Instruction Manual. Tianjin Dongtai Technology Development Co., Ltd., 2004 [5] Fan Yizhi, Chen Liyuan. Visual Basic and RS-232 Serial Communication Control [M]. Beijing: Tsinghua University Press, 2002: 54-110 [6] Li Xiangjiang. Visual Basic Serial Communication Technology [J]. Electrical Drive Automation, 2004, 20(6): 9-11