API for MinimalModbus

MinimalModbus: A Python driver for Modbus RTU/ASCII via serial port.

minimalmodbus.MODE_RTU = 'rtu'

Use Modbus RTU communication.

minimalmodbus.MODE_ASCII = 'ascii'

Use Modbus ASCII communication.

minimalmodbus.BYTEORDER_BIG = 0

Use big endian byteorder.

minimalmodbus.BYTEORDER_LITTLE = 1

Use little endian byteorder.

minimalmodbus.BYTEORDER_BIG_SWAP = 2

Use big endian byteorder, with swap.

minimalmodbus.BYTEORDER_LITTLE_SWAP = 3

Use litte endian byteorder, with swap.

class minimalmodbus.Instrument(port: Union[str, serial.serialposix.Serial], slaveaddress: int, mode: str = 'rtu', close_port_after_each_call: bool = False, debug: bool = False)[source]

Bases: object

Instrument class for talking to instruments (slaves).

Uses the Modbus RTU or ASCII protocols (via RS485 or RS232).

Args:
  • port: The serial port name, for example /dev/ttyUSB0 (Linux), /dev/tty.usbserial (OS X) or COM4 (Windows). It is also possible to pass in an already opened serial.Serial object (new in version 2.1).
  • slaveaddress: Slave address in the range 0 to 247. Address 0 is for broadcast, and 248-255 are reserved.
  • mode: Mode selection. Can be minimalmodbus.MODE_RTU or minimalmodbus.MODE_ASCII.
  • close_port_after_each_call: If the serial port should be closed after each call to the instrument.
  • debug: Set this to True to print the communication details
address = None

Slave address (int). Most often set by the constructor (see the class documentation).

Slave address 0 is for broadcasting to all slaves (no responses are sent). It is only possible to write infomation (not read) via broadcast. A long delay is added after each transmission to allow the slowest slaves to digest the information.

New in version 2.0: Support for broadcast

mode = None

Slave mode (str), can be minimalmodbus.MODE_RTU or minimalmodbus.MODE_ASCII. Most often set by the constructor (see the class documentation). Defaults to RTU.

Changing this will not affect how other instruments use the same serial port.

New in version 0.6.

precalculate_read_size = None

If this is False, the serial port reads until timeout instead of just reading a specific number of bytes. Defaults to True.

Changing this will not affect how other instruments use the same serial port.

New in version 0.5.

debug = None

Set this to True to print the communication details. Defaults to False.

Most often set by the constructor (see the class documentation).

Changing this will not affect how other instruments use the same serial port.

clear_buffers_before_each_transaction = None

If this is True, the serial port read and write buffers are cleared before each request to the instrument, to avoid cumulative byte sync errors across multiple messages. Defaults to True.

Changing this will not affect how other instruments use the same serial port.

New in version 1.0.

close_port_after_each_call = None

If this is True, the serial port will be closed after each call. Defaults to False.

Changing this will not affect how other instruments use the same serial port.

Most often set by the constructor (see the class documentation).

handle_local_echo = None

Set to to True if your RS-485 adaptor has local echo enabled. Then the transmitted message will immeadiately appear at the receive line of the RS-485 adaptor. MinimalModbus will then read and discard this data, before reading the data from the slave. Defaults to False.

Changing this will not affect how other instruments use the same serial port.

New in version 0.7.

serial = None

The serial port object as defined by the pySerial module. Created by the constructor.

Attributes that could be changed after initialisation:

  • port (str): Serial port name.
    • Most often set by the constructor (see the class documentation).
  • baudrate (int): Baudrate in Baud.
    • Defaults to 19200.
  • parity (use PARITY_xxx constants): Parity. See the pySerial module.
    • Defaults to serial.PARITY_NONE.
  • bytesize (int): Bytesize in bits.
    • Defaults to 8.
  • stopbits (use STOPBITS_xxx constants): Number of stopbits. See pySerial.
    • Defaults to serial.STOPBITS_ONE.
  • timeout (float): Read timeout value in seconds.
    • Defaults to 0.05 s.
  • write_timeout (float): Write timeout value in seconds.
    • Defaults to 2.0 s.
roundtrip_time

Latest measured round-trip time, in seconds. Read only.

Note that the value is None if no data is available.

The round-trip time is the time from minimalmodbus sends request data, to the time it receives response data from the instrument. It is basically the time spent waiting on external communication.

Note that mimimalmodbus also sleeps (not included in the round trip time), for example to fulfill the inter-message time interval or to give slaves time to process broadcasted information.

New in version 2.0

read_bit(registeraddress: int, functioncode: int = 2) → int[source]

Read one bit from the slave (instrument).

This is for a bit that has its individual address in the instrument.

Args:
  • registeraddress: The slave register address.
  • functioncode Modbus function code. Can be 1 or 2.
Returns:
The bit value 0 or 1.
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_bit(registeraddress: int, value: int, functioncode: int = 5) → None[source]

Write one bit to the slave (instrument).

This is for a bit that has its individual address in the instrument.

Args:
  • registeraddress: The slave register address.
  • value: 0 or 1, or True or False
  • functioncode: Modbus function code. Can be 5 or 15.
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_bits(registeraddress: int, number_of_bits: int, functioncode: int = 2) → List[int][source]

Read multiple bits from the slave (instrument).

This is for bits that have individual addresses in the instrument.

Args:
  • registeraddress: The slave register start address.
  • number_of_bits: Number of bits to read
  • functioncode: Modbus function code. Can be 1 or 2.
Returns:
A list of bit values 0 or 1. The first value in the list is for the bit at the given address.
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_bits(registeraddress: int, values: List[int]) → None[source]

Write multiple bits to the slave (instrument).

This is for bits that have individual addresses in the instrument.

Uses Modbus functioncode 15.

Args:
  • registeraddress: The slave register start address.
  • values: List of 0 or 1, or True or False. The first value in the list is for the bit at the given address.
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_register(registeraddress: int, number_of_decimals: int = 0, functioncode: int = 3, signed: bool = False) → Union[int, float][source]

Read an integer from one 16-bit register in the slave, possibly scaling it.

The slave register can hold integer values in the range 0 to 65535 (“Unsigned INT16”).

Args:
  • registeraddress: The slave register address.
  • number_of_decimals: The number of decimals for content conversion.
  • functioncode: Modbus function code. Can be 3 or 4.
  • signed: Whether the data should be interpreted as unsigned or signed.

Note

The parameter number_of_decimals was named numberOfDecimals before MinimalModbus 1.0

If a value of 77.0 is stored internally in the slave register as 770, then use number_of_decimals=1 which will divide the received data by 10 before returning the value.

Similarly number_of_decimals=2 will divide the received data by 100 before returning the value.

Some manufacturers allow negative values for some registers. Instead of an allowed integer range 0 to 65535, a range -32768 to 32767 is allowed. This is implemented as any received value in the upper range (32768 to 65535) is interpreted as negative value (in the range -32768 to -1).

Use the parameter signed=True if reading from a register that can hold negative values. Then upper range data will be automatically converted into negative return values (two’s complement).

signed Data type in slave Alternative name Range
False Unsigned INT16 Unsigned short 0 to 65535
True INT16 Short -32768 to 32767
Returns:
The register data in numerical value (int or float).
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_register(registeraddress: int, value: Union[int, float], number_of_decimals: int = 0, functioncode: int = 16, signed: bool = False) → None[source]

Write an integer to one 16-bit register in the slave, possibly scaling it.

The slave register can hold integer values in the range 0 to 65535 (“Unsigned INT16”).

Args:
  • registeraddress: The slave register address.
  • value (int or float): The value to store in the slave register (might be scaled before sending).
  • number_of_decimals: The number of decimals for content conversion.
  • functioncode: Modbus function code. Can be 6 or 16.
  • signed: Whether the data should be interpreted as unsigned or signed.

Note

The parameter number_of_decimals was named numberOfDecimals before MinimalModbus 1.0

To store for example value=77.0, use number_of_decimals=1 if the slave register will hold it as 770 internally. This will multiply value by 10 before sending it to the slave register.

Similarly number_of_decimals=2 will multiply value by 100 before sending it to the slave register.

As the largest number that can be written to a register is 0xFFFF = 65535, the value and number_of_decimals should max be 65535 when combined. So when using number_of_decimals=3 the maximum value is 65.535.

For discussion on negative values, the range and on alternative names, see read_register().

Use the parameter signed=True if writing to a register that can hold negative values. Then negative input will be automatically converted into upper range data (two’s complement).

Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_long(registeraddress: int, functioncode: int = 3, signed: bool = False, byteorder: int = 0, number_of_registers: int = 2) → int[source]

Read a long integer (32 or 64 bits) from the slave.

Long integers (32 bits = 4 bytes or 64 bits = 8 bytes) are stored in two or four consecutive 16-bit registers in the slave respectively.

Args:
  • registeraddress: The slave register start address.
  • functioncode: Modbus function code. Can be 3 or 4.
  • signed: Whether the data should be interpreted as unsigned or signed.
  • byteorder: How multi-register data should be interpreted. Use the BYTEORDER_xxx constants. Defaults to minimalmodbus.BYTEORDER_BIG.
  • number_of_registers: The number of registers allocated for the long. Can be 2 or 4. (New in version 2.1)
number_of_registers signed Slave data type Range
2 False Unsigned INT32 0 to 4294967295
2 True INT32 -2147483648 to 2147483647
4 False Unsigned INT64 0 to approx 1.8E19
4 True INT64 Approx -9.2E18 to 9.2E18
Returns:
The numerical value.
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_long(registeraddress: int, value: int, signed: bool = False, byteorder: int = 0, number_of_registers: int = 2) → None[source]

Write a long integer (32 or 64 bits) to the slave.

Long integers (32 bits = 4 bytes or 64 bits = 8 bytes) are stored in two or four consecutive 16-bit registers in the slave respectively.

Uses Modbus function code 16.

For discussion on number of bits, number of registers and the range, see read_long().

Args:
  • registeraddress: The slave register start address.
  • value: The value to store in the slave.
  • signed: Whether the data should be interpreted as unsigned or signed.
  • byteorder: How multi-register data should be interpreted. Use the BYTEORDER_xxx constants. Defaults to minimalmodbus.BYTEORDER_BIG.
  • number_of_registers: The number of registers allocated for the long. Can be 2 or 4. (New in version 2.1)
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_float(registeraddress: int, functioncode: int = 3, number_of_registers: int = 2, byteorder: int = 0) → float[source]

Read a floating point number from the slave.

Floats are stored in two or more consecutive 16-bit registers in the slave. The encoding is according to the standard IEEE 754.

There are differences in the byte order used by different manufacturers. A floating point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this implementation the data will be sent as '\x3f\x80' and '\x00\x00' to two consecutetive registers by default. Make sure to test that it makes sense for your instrument. If not, change the byteorder argument.

Args:
  • registeraddress : The slave register start address.
  • functioncode: Modbus function code. Can be 3 or 4.
  • number_of_registers: The number of registers allocated for the float. Can be 2 or 4.
  • byteorder: How multi-register data should be interpreted. Use the BYTEORDER_xxx constants. Defaults to minimalmodbus.BYTEORDER_BIG.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

Type of floating point in slave Size Registers Range
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308
Returns:
The numerical value.
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_float(registeraddress: int, value: Union[int, float], number_of_registers: int = 2, byteorder: int = 0) → None[source]

Write a floating point number to the slave.

Floats are stored in two or more consecutive 16-bit registers in the slave.

Uses Modbus function code 16.

For discussion on precision, number of registers and on byte order, see read_float().

Args:
  • registeraddress: The slave register start address.
  • value (float or int): The value to store in the slave
  • number_of_registers: The number of registers allocated for the float. Can be 2 or 4.
  • byteorder: How multi-register data should be interpreted. Use the BYTEORDER_xxx constants. Defaults to minimalmodbus.BYTEORDER_BIG.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_string(registeraddress: int, number_of_registers: int = 16, functioncode: int = 3) → str[source]

Read an ASCII string from the slave.

Each 16-bit register in the slave are interpreted as two characters (each 1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes).

International characters (Unicode/UTF-8) are not supported.

Args:
  • registeraddress: The slave register start address.
  • number_of_registers: The number of registers allocated for the string.
  • functioncode: Modbus function code. Can be 3 or 4.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

Returns:
The string.
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_string(registeraddress: int, textstring: str, number_of_registers: int = 16) → None[source]

Write an ASCII string to the slave.

Each 16-bit register in the slave are interpreted as two characters (each 1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes).

Uses Modbus function code 16.

International characters (Unicode/UTF-8) are not supported.

Args:
  • registeraddress: The slave register start address.
  • textstring: The string to store in the slave, must be ASCII.
  • number_of_registers: The number of registers allocated for the string.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

If the textstring is longer than the 2*number_of_registers, an error is raised. Shorter strings are padded with spaces.

Returns:
None
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_registers(registeraddress: int, number_of_registers: int, functioncode: int = 3) → List[int][source]

Read integers from 16-bit registers in the slave.

The slave registers can hold integer values in the range 0 to 65535 (“Unsigned INT16”).

Args:
  • registeraddress: The slave register start address.
  • number_of_registers: The number of registers to read, max 125 registers.
  • functioncode: Modbus function code. Can be 3 or 4.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

Any scaling of the register data, or converting it to negative number (two’s complement) must be done manually.

Returns:
The register data. The first value in the list is for the register at the given address.
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_registers(registeraddress: int, values: List[int]) → None[source]

Write integers to 16-bit registers in the slave.

The slave register can hold integer values in the range 0 to 65535 (“Unsigned INT16”).

Uses Modbus function code 16.

The number of registers that will be written is defined by the length of the values list.

Args:
  • registeraddress: The slave register start address.
  • values: The values to store in the slave registers, max 123 values. The first value in the list is for the register at the given address.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

Any scaling of the register data, or converting it to negative number (two’s complement) must be done manually.

Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
exception minimalmodbus.ModbusException[source]

Bases: OSError

Base class for Modbus communication exceptions.

Inherits from IOError, which is an alias for OSError in Python3.

exception minimalmodbus.SlaveReportedException[source]

Bases: minimalmodbus.ModbusException

Base class for exceptions that the slave (instrument) reports.

exception minimalmodbus.SlaveDeviceBusyError[source]

Bases: minimalmodbus.SlaveReportedException

The slave is busy processing some command.

exception minimalmodbus.NegativeAcknowledgeError[source]

Bases: minimalmodbus.SlaveReportedException

The slave can not fulfil the programming request.

This typically happens when using function code 13 or 14 decimal.

exception minimalmodbus.IllegalRequestError[source]

Bases: minimalmodbus.SlaveReportedException

The slave has received an illegal request.

exception minimalmodbus.MasterReportedException[source]

Bases: minimalmodbus.ModbusException

Base class for exceptions that the master (computer) detects.

exception minimalmodbus.NoResponseError[source]

Bases: minimalmodbus.MasterReportedException

No response from the slave.

exception minimalmodbus.LocalEchoError[source]

Bases: minimalmodbus.MasterReportedException

There is some problem with the local echo.

exception minimalmodbus.InvalidResponseError[source]

Bases: minimalmodbus.MasterReportedException

The response does not fulfill the Modbus standad, for example wrong checksum.