Modbus quick start tutorial of cloud protocol on IOT

Programmer base 2021-10-14 04:37:17

This article is reprinted. ,  Original author : Mr. source code , The article links :, Do not use for commercial purposes , If there is any infringement , Please inform to delete .

The Internet of things IoT Cloud protocol Modbus Quick start tutorial

What is? Modbus

Modbus and OPC UA、mqtt The essence is the same , It is an application layer protocol for multiple devices to communicate with each other .Modbus On 1979 The year was born in Modicon company ( Present quilt Schneider Company purchase ), Once launched, it has gradually become a popular standard in industrial system because of its simple and open communication mode .Modbus The main international organizations are Modbus-IDA, Be responsible for promoting Modbus Standards and for Modbus Product certification .Modbus See you on the official website, The website mainly includes agreement documents ,Modbus Products and manufacturers .

Previous The Internet of things IoT Agreement OPC UA Quick start tutorial I mentioned OPC UA It is a common protocol in the industrial field , In fact, in the field of industry Modbus Than OPC/OPC UA More common , There are many data acquisition devices on the market ( Such as temperature and humidity collection ) All use Modbus agreement ;OPC UA A large number of proper nouns ( Such as node 、 service 、 Quote, etc ) It always makes beginners confused , and Modbus Than OPC UA It's so simple , Simplicity includes :

  • Modbus First use RS232,RS485 And other serial links as the bottom communication mode , The interface chip of serial bus has low cost , And the wiring is simple and convenient ;
  • Modbus Is a simple application layer protocol , Its information format is simple and easy to understand , The details of the agreement are described below ;
  • Modbus There are many related documents .

What is a bus / What is? Modbus Bus

Modbus Medium bus It means bus , So what is a bus ? Bus is a kind of network topology , The network topology has star 、 Ring 、 Tree shape 、 Bus type, etc , Bus topology is one of them . Whatever the network topology , Finally, it is to realize the communication between multiple devices .

The two devices communicate with each other , Just connect the two devices with one line .

 Network topology Network topology

The three devices communicate with each other , Connecting two by two requires 3 line .

 Network topology Network topology

The four devices communicate with each other , Connecting two by two requires 6 line .

 Network topology Network topology

Obviously , As the number of devices increases , The lines needed to connect two by two grow exponentially , So it's definitely not appropriate to connect two by two , Bus topology solves the problem of connecting and communicating multiple devices by introducing bus .

 Bus network topology Bus network topology

Multiple devices reuse the same bus , Reduce the complexity of wiring ; However, when reusing the same bus, new problems will be encountered , When multiple devices send data at the same time , Data conflict . To avoid data conflicts , There are many solutions , For example, Ethernet uses CSMA/CD( Carrier sense multiple access / Collision detection ),CSMA The protocol requires the device to listen to the bus before sending data / channel , If the bus is idle , The device can send data , If the bus is busy , Then the device cannot send data ; and Modbus A simpler way to avoid conflict , Master slave communication mode .

Modbus Master-slave communication mode

Modbus In order to avoid data conflict of multiple devices , A single host is used / Multi slave mode , That is, there can only be one host in the whole system (Master) And multiple slaves (Slave).

Modbus Master-slave communication mode Modbus Master-slave communication mode

Modbus Use request - Mode of response , And Modbus The standard stipulates ,Modbus Requests can only be initiated by the host , The master sends the request data to the slave , The slave only receives the request data from the host , To send response data to the bus ; The whole process The slave can only respond passively , Cannot actively send data to the bus . Through master-slave communication mode ,Modbus Avoid the conflict of multiple device data ;

Modbus Master-slave communication mode Modbus Master-slave communication mode

To avoid data conflicts , The host is not allowed to send multiple messages to the bus in parallel , After the host sends the request data , You must wait until the slave answers the data or times out , To send the next request ; After the master sends information to the slave , The host will start a wait timeout timer , If the master does not receive the response message from the slave , Only after the wait timeout timer expires , Before you can send the next request information .

Each slave has a unique slave address , When the host initiates a request , The request data carries the target slave address ; The host sends the request data to the bus , All slaves on the bus will receive the request , The slave opportunity checks whether the slave address carried in the request is its own , If it is you, reply to the response data , If not yourself, ignore the request .

Modbus Business model of

Modbus Our business model is also relatively simple , Mr. source put Modbus The business model is abbreviated as “ Read and write data ” Model , namely adopt “ read ” Some ( Memory ) Address data , Get the data collected by the device ( Or the status of the device ); adopt “ Write ” Some ( Memory ) Address data , Realize the control of the device ( For example, configure the parameters of the device ).

Modbus In the standard , hold Modbus The address space is divided into 4 Regions .

Modbus Data model Modbus Data model

this 4 Regions , In many documents, it is called 4 A register .

Modbus Register classification Modbus Register classification

It's called a register , It's a historical name ,Modbus At first, it was used to operate PLC The register of , Now you can generalize registers into memory ,4 Each register is equivalent to 4 Just one memory partition .
As for the name of the register , Such as register 0 The name of the is coil (coils) state , It also uses the historical name ( The coil is the coil on the relay , The relay is an electronic switch , Energize the coil , The relay is on , De energize the coil , The relay is off , So the coil is only on / Turn off these two states ), If you don't understand what a coil is , The name coil can be completely ignored , Just remember the register 0 The corresponding data is only 0/1 These two values that will do , This is also the image above single bit The meaning of ( Just corresponds to the coil on / Turn off these two states , In fact, it tells the user through the name of coil , The data in this register partition is only 0/1), It means “ read ” register 0 Data for any address , The data read is not 0 Namely 1, Read register 0 Of 0x0000 Address data , What I read is 0( perhaps 1), Read register 0 Of 0x0001 Address data , What I read is also 0( perhaps 1).

Please ignore the name of the register ,4 The essence of each register is “ Memory ”, Each register contains a memory address space ( The address value range of each register is 0x0000-0xFFFF), What users need to do is “ Read and write memory ”.

4 Registers are classified according to their functions , Like registers 0 Can read but write , And registers 1 read-only ; register 0 The data of single bit( No 0 Namely 1), And registers 3 The data of 16-bit world( Two bytes ), This means reading registers 3 Of 0x0000 Address data , What you read is 2 Bytes of data , Read register 3 Of 0x0001 Address data , It's also read out 2 Bytes of data .

Be careful ,4 The two kinds of registers are registers 0、 register 1、 register 3、 register 4, There are no registers 2, As for why there are no registers 2, It is estimated that it is also caused by historical reasons ?!

 It's all my fault It's all my fault

Modbus Message format / Message frame format

Modbus Yes 3 Kind of message :

  • Modbus ASCII: Use ASCII code , Bottom use RS458 Serial link communication
  • Modbus RTU: Use raw binary , Bottom use RS458 Serial link communication
  • Modbus TCP: Use raw binary , Bottom use TCP signal communication

The message body of these three messages ( Including slave address + Function code + Data fields ) All the same , There is no essential difference between the three . because Modbus ASCII Use ASCII code , comparison Modbus RTU The original binary used , The former takes up more space , Low transmission efficiency , therefore Modbus ASCII Is not commonly used , Here we mainly introduce Modbus RTU and Modbus TCP.

Modbus RTU

Modbus RTU The message format is shown in the following figure .

Modbus RTUModbus RTU

Slave address (Slave Address)

The slave address of the device is used to identify the uniqueness of the device , You can customize the slave address of the configuration device , As long as the slave address of each device on the bus is unique , No conflict , Slave address range :1-247,0 For broadcast address ,248-255 Reserved address for .

Function code (Function Code)

The function code corresponds to a service provided by the device / function ,Modbus The function code is divided into 3 class :

  • Public function code (Public Function Codes):Modbus Standard defined , Function code with clear function , Such function codes can be queried Modbus Standard documents ( )
  • User defined function code (User-Defined Function Codes): The function code customized by the equipment according to requirements , Value range 65-72 and 100-110;
  • Keep the function code (Reserved Function Codes): It is not used at present , Negligible

although Modbus Many common function codes are defined in the standard , But in the actual scenario , The only common is reading / Write 4 A register related function code , Reading and writing are divided into Single Reading and writing ( Read only write data to one address at a time ) and Multiple Reading and writing ( Read and write data of multiple addresses at one time ):

  • 0x01 Multiple Coils Batch read register 0
  • 0x02 Multiple Discrete Inputs Batch read register 1
  • 0x03 Multiple Holding Registers Batch read register 4
  • 0x04 Multiple Input Registers Batch read register 3
  • 0x05 Single Coil Write a single register 0
  • 0x06 Single Holding Register Write a single register 4
  • 0x07 Read Exception Status Read exception status
  • 0x0F Multiple Coils Batch write register 0
  • 0x10 Multiple Holding Registers Batch write register 4

Development Modbus Equipment time , The corresponding function code can be selected according to the equipment requirements :

  • When the equipment data is a switching value 0/1, The optional function codes for reading device data are 0x01 and 0x02;
  • When the equipment data is a switching value 0/1, At the same time, only reading and writing are allowed , Read the function code of the device data Can only choose 0x02, Because the function code 0x01 The corresponding register 0 Allow writing ;
  • When the data length is greater than 2 Byte length ( such as 4 byte ), You can select function codes for batch reading and writing ( Read function codes in batches 0x03 and 0x04, Write function codes in batches 0x10), Note that the big end will be encountered at this time / Small end problem ( in addition ,4 The data of bytes corresponds to integer or floating point number , It depends on how the application parses 4 Bytes of data , and Modbus The standard is not off )

When you buy Modbus Equipment time , Generally, you need to query the function codes used by the equipment from the supporting description documents of the equipment 、 And the meaning of reading and writing data .

Data fields (Data)

The data field is used to store the data to be communicated , That's what they say Payload. Data fields are in bytes , Variable length , The format of the data field is also variable , The specific format is determined by the function code , For some function codes , The data field can be empty , Different function codes , The data field format is different , Can pass Modbus The function code of the standard document queries the specific data field format , The following figure shows the function code 0x03 Corresponding data field format .

Modbus Data fields PayloadModbus Data fields Payload

0x03 It's batch reading , Therefore, the data field of the request message includes the data to be read “ register ” The starting data address of 、 Number of registers to read .

Data address

Modbus The business model is “ Read and write data ” Model , When reading and writing, you must have a data address , Theoretically, the value range of the data address of each register is 0x0000-0xFFFF, Be careful The data addresses of different kinds of registers are independent , Registers can have 0x0000, register 2 There can be 0x0000, Although the data address is the same , But reading and writing data do not affect each other .
In fact , For historical reasons , The data address of a register has a variety of notation .

Modbus Data address representation Modbus Data address representation

Although there are similarities and differences in the notation , But it's better to distinguish , Just remember the following features :

  • Address range ( Maximum ) All are 0x0000-0xFFFF, But it's divided into 16 Hexadecimal notation or 10 Decimal notation
  • The front of the address , Some have Prefix of register sequence number , Some have not , See the red box in the figure above , Register serial number corresponds to 4 A register
  • 16 The address of the hexadecimal representation is from 0 Start , The address of decimal notation is from 1 Start

CRC check

Verify the correctness and integrity of the data , The calculation method is fixed , Calculate... According to a fixed algorithm CRC value .

Modbus TCP

although RS485 Serial link is simpler than Ethernet link , But given the popularity of Ethernet ,Modbus introduce TCP/IP As a means of communication .Modbus It's the application layer protocol , Regardless of the underlying use RS485 The link is still TCP, The application layer changes little .

Modbus TCPModbus TCP

contrast Modbus RTU message ,Modbus TCP The message has the following similarities and differences :

  • Function code and data field Modbus RTU identical
  • Removed the slave address ( That is, the additional address in the figure above ), because TCP It's connection-oriented ,TCP It must be based on IP Address to establish a one-to-one connection , After the connection is established , The slave address is no longer needed ;
  • The error check is removed , because TCP It's a reliable transmission ,TCP The transport layer has done data verification ,Modbus The application layer can no longer verify ;
  • Added transaction flag , This can be regarded as self increasing ID To identify different messages , because Modbus The standard does not allow multiple messages to be sent in parallel , Therefore, the transaction flag is filled as 0 Also no problem ;
  • Added protocol identifier ,Modbus The protocol value is fixed to 0x00;
  • Increased data length , namely Modbus TCP The length of the message , because TCP It's streaming data , The data length needs to be used to identify the boundary of two messages ;
  • Added unit identifier , Here you can fill in 0 Or fill in the slave address ( It can be used for the gateway to forward the request to the slave );

Mentioned earlier Modbus The master-slave communication mode is mainly to avoid data conflict of multiple devices , and TCP The bottom layer has been used CSMA/CD Solved the problem of data conflict , and TCP It's full duplex communication (RS485 The link is half duplex ), It means Modbus TCP There will be no conflict when the slave actively sends messages , But if the slave actively sends a message , It doesn't fit Modbus Standard .TCP It's connection-oriented , be based on Modbus TCP Realize multi master / Multi slave communication is also feasible , There is no conflict , But it doesn't meet Modbus Standard .

TCP There are clients in (Client) And the server (Server), Corresponding to Modbus in ,Modbus host (Master) Corresponding TCP client (Client),Modbus Slave (Slave) Corresponding TCP The server (Server), Use Modbus TCP when , Use standard first socket Establish a client to server connection TCP Connect , Send after establishment Modbus TCP A message is enough .

Modbus And Hello World

Modbus Software , The more popular is Modbus Poll And Modbus Slave, The function is also relatively perfect , It's just paid software ( You can try 30 God ). As Hello World The presentation of , Mr. source found a free Modbus Simulation software EasyModbusTCP, Can pass download .

function Modbus TCP Server( I.e. slave )

double-click EasyModbusServerSimulator.exe start-up , The program is automatically run locally IP establish TCP The server , port 502.

Modbus TCP ServerModbus TCP Server

function Modbus TCP Client( I.e. mainframe )

double-click EasyModbusClientExample.exe, Start client . Click... As shown below connect, Connect to server .

Modbus TCP ClientModbus TCP Client

Reading data

Client interface , Click on “Read Coils -FC1” Button , Can read registers 0 The data of .

Modbus Reading data Modbus Reading data

Above picture , Users can customize the starting address of reading data 、 Number of registers to read ; You can also view the request message and response message used in the reading process .

Writing data

The following figure shows the write register 4 The process of , Please refer to... In the figure 1-5 The order of

Modbus Writing data Modbus Writing data

After writing data successfully , Read the written data again , Correctly read the... Written in the previous step 110.

Modbus Writing data Modbus Writing data

Use Modbus On the cloud

because Modbus Master slave communication mode , The slave can only respond passively , Unable to actively report data , therefore Modbus In fact, it's not suitable for the cloud , But there are a lot of Modbus equipment , If the support Modbus If you go to the cloud , You can quickly connect existing devices to the cloud , It's still necessary .

Modbus Cloud gateway Modbus Cloud gateway

Above, Modbus Provided in the standard documentation Modbus Communication block diagram , The concept of gateway is introduced in the figure , If you want to go to the cloud , You need to use the gateway . The gateway needs to have Wifi/4G/ so , Gateway through TCP/IP Communicate with the cloud , Specifically, the cloud has the following two ways .

Mode one : Cloud as Modbus host

Modbus Cloud gateway Modbus Cloud gateway

  • The cloud software platform is used as Modbus host , The cloud regularly sends request messages to the gateway , The gateway forwards the request message Modbus On the bus ,Modbus After the slave on the bus receives the request , Return the response data to Modbus Bus , The gateway reads the response message and forwards it to the cloud ;
  • Between cloud and gateway Modbus TCP Message communication , Between the gateway and the device Modbus RTU, You can also use Modbus TCP Message communication ;
  • The gateway acts as a forwarding role , Forward data between cloud and slave devices , The gateway also acts as a conversion protocol , For example Modbus TCP Convert to Modbus RTU;
  • The cloud needs to send request messages constantly , Equivalent to constant polling , When the number of slave devices is large , The polling pressure on the cloud is high , Communication bandwidth requirements are also relatively high .

Mode two : Gateway as Modbus host

Modbus Cloud gateway Modbus Cloud gateway

  • Gateway as Modbus host , The gateway actively sends the request message to Modbus On the bus , Then receive the response message from the slave ; After the gateway receives the slave response message , Other protocols can be used ( such as mqtt) Forward the response information to the cloud .
  • The gateway acts as Modbus host , You also need to be a client connected to the cloud ( such as Mqtt client ) Actively report the polled data to the cloud ;
  • The information about how the gateway polls the slave needs to be configured from the cloud to the gateway , Configuration is a little troublesome , But the polling pressure is scattered on the gateway , It is more in line with the idea of edge calculation .

Modbus Advantages and disadvantages

Modbus advantage : Simple protocol , The cost of interface chip is low ;

Modbus shortcoming : Poor real-time performance ( The slave cannot actively report data , Must rely on host polling ), Low bus utilization , Low transmission rate , in addition RS485 Weak anti-interference , Node errors affect the entire bus . If Modbus Can't meet their own needs , have access to CAN Bus .

Please bring the original link to reprint ,thank
Similar articles