The blog

Using Modbus prototype development

Programmers write on the notebook screen python code, Java script, HTML code
Alex Pohjanpelto
Alex Pohjanpelto
Published: Nine month 7, 2021
Industrial manufacturing and process
Industrial measurement
Life science

You are in the prototype development, or looking for a way of economical and ensure quality of application of temperature and humidity measurement?Do you know some basic knowledge about programming languages such as Python?If you understand, so I want to show you how to only through a HMP110 probe, a USB cable (219690) and a service installed Python 3 computers to easily record data for a long time.I will take you to understand all aspects of the code, but if you are not interested in explanations, you can jump straight to the end of this article, get the complete code.In addition to be sure, this is just a sample script for demo Modbus communication.

library

Before introduce code, let the first thing we know about the library, we will use the important of which is pymodbus.We use this library to build communication by Modbus RTU and probe, specific operation from pymodbus. Client. The sync import ModbusSerialClient.We use struct library will word processing for different types of variables, using the time rate of change of polling, use datetime library for reading data of the time and date, in addition, we import the argparse library, transfer parameters from the command line to the code.

The from pymodbus. Client. Sync import ModbusSerialClient as ModbusClient
The import struct
The import time
Import a datetime
The import argparse

parameter

In order to help to improve the flexibility of the code, I added some parameters.Can let we don't need to change the code using the above parameters, can from the command line is more easy to change.I think that may help the parameters of the communication port, data storage file name, the address of the probe, the polling frequency and length of data records.

Parser = argparse. ArgumentParser (
Description = "Modbus data logger"
)
Parser. Add_argument (' port 'help = "The COM port where The probe is attached")
Parser. Add_argument (' -f ', '- The file, help = "The file name to store The data (The default data. The CSV)", The default = "data. CSV)"
Parser. Add_argument (' a ', '- The address, help = "The address of The probe (default 240)", The default = 240, type = int)
Parser. Add_argument (' -r ', "rate", help = "The poll rate in seconds (default 1)", The default = 1, type = float)
Parser. Add_argument (' -l ', '- length, help = "The length of time in hours to data log (default 9999999)", type = float, default = 9999999)
Args = parser. Parse_args ()

Modbus connection

We first need to initialize the new serial Modbus client, the client should have according to the probe is set up correctly.In this example, the parameter set must include response timeout, communication mode, communication port, baud rate, stop bits and parity.Modbus RTU communication mode for the RTU, port depends on your computer, so I will be in the following section shows how to identify the correct port.Because of other parameters is determined by probe setup, so you need to refer to probe the data table, access to the appropriate value.In general, for visa probe, baud rate should be 19200, stop bit is 2, and white parity checking.

The probe = ModbusClient (method = 'rtu, port = args. The port, the timeout = 1, baudrate = 19200, stopbits = 2, parity =' N ')

Read keep register

Now let's create a function to read the probe keep registers.We want to call on the section create instances of the Modbus client read_holding_registers () method to read the register.We need to specify the starting address of the register, the number of registers and probe the slave address.We will be received from the register of the low byte sequence format 16-bit word data, later, we must transform it into a 32-bit floating point value.

Def holding_registers_data () :
Try:
Registers the probe of = read_holding_registers (address = 0, count = 10, unit = args. The address). The registers
Except the Exception as e:
Print (e)
Return False, None, None, None
Try:
Rh = data_from_register (registers, 1)
T = data_from_register (registers, 3)
Dp = data_from_register (9) registers,

Except the Exception as e:
Print (e)
Return False, None, None, None
Return True, rh, t, dp

Converts the value of the register to 32-bit value

Register values stored in the form of a 16-bit integer, we need to transform it into a 32-bit floating point format.For this, I created a function, it can obtain the value of the register and register the index, and returns the index data of 32 bit floating point value.We adopt the module structure to carry out the transformation

Def data_from_register (registers, I) :
Return struct. Unpack ('!F ', bytes. Fromhex (' {0:04 x} '. The format (registers [I]) + '} {0:04 x '. The format (registers [I - 1)))) [0]

Record the data

Given that we have already can read keep register and converts the value of the register to 32 bit floating point value, we need to create a these values can be stored in the function of the CSV file.To this end, I created a named data_logger () function.It can call the function holding_registers_data (), and to date/time, relative humidity, temperature, dew point data appended to the file format to be obtained.

Def data_logger () :
The probe. The connect ()
Successful, rh, t, dp = holding_registers_data ()
If (successful) :
Dt = datetime. Datetime. Now ()

Try:
With the open (args. The file, "a") as f:
Rh in line = f "{dt}, {}, {t}, {dp} \ n"
Print (line)
F.w rite (line)
Except the Exception as e:
Print (e)
The probe. The close ()
Time. Sleep (args. Rate)

The else:
The probe. The close ()
Time. Sleep (0.5)

To determine the probe communication port

First of all, make sure you probe can correctly connected to the computer.

Windows
In the Windows operating system, you can be found in "device manager" COM port of the equipment.You want to open the "device manager" window, please open the lower left corner of the screen "start" menu, and then enter the "device manager".It will show in search results, click on the icon or press the Enter key on the keyboard to open the window.Click "port (COM and LPT)" the arrow to expand next to the port.You will see is listed as "Vaisala USB Device" a Device, it listed next to the COM port name, in our case should be COM6.

The Image
Determining the communication port of the probe

Linux
In Linux, you can use the terminal type the command "dmesg | grep tty" to determine the communication port.In all the return statement, there will be a similar to "' cp210x converter now attached to ttyUSBn" statements, including ttyUSBn is port.

Run the code

To run the script, you must install all of the library.If you need, you can use the PIP command

Pip3 install -u pymodbus
To install pymodbus. The other libraries should already has with The python 3 package.
In a command prompt and navigate to the directory where they python script is stored and type
Python Modbus_RTU - h

In order to obtain the parameters of operation.The command prompt should show this process.Below is the output content of screenshots.

The Image
Terminal

Communication port is required parameters, other parameters have default values, you can according to your own preferences to change.Communication port parameters do not need identifier, can be placed anywhere after the file name.But other optional parameters need identifier.
The following format is long and short shows a typical example of command:

Python. \ Modbus_RTU - file datalog. CSV - address - rate of 10-240 length 48 COM6
Python. \ Modbus_RTU - f datalog. CSV - a 240-48 COM6 r 10 - l

Download the complete codeandWatch the Modbus 101 online seminars.