API for MinimalModbus

MinimalModbus: A Python driver for Modbus RTU/ASCII via serial port (via USB, RS485 or RS232).

class minimalmodbus.Instrument(port, slaveaddress, mode='rtu', close_port_after_each_call=False, debug=False)[source]

Instrument class for talking to instruments (slaves).

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

Args:
  • port (str): The serial port name, for example /dev/ttyUSB0 (Linux), /dev/tty.usbserial (OS X) or COM4 (Windows).
  • slaveaddress (int): Slave address in the range 1 to 247 (use decimal numbers, not hex). Address 0 is for broadcast, and 248-255 are reserved.
  • mode (str): Mode selection. Can be MODE_RTU or MODE_ASCII.
  • close_port_after_each_call (bool): If the serial port should be closed after each call to the instrument.
  • debug (bool): Set this to True to print the communication details
address = None

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

mode = None

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

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 (probably int): Parity. See the pySerial module for documentation.
    • Defaults to serial.PARITY_NONE.
  • bytesize (int): Bytesize in bits.
    • Defaults to 8.
  • stopbits (int): The number of stopbits.
    • Defaults to 1.
  • 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.
read_bit(registeraddress, functioncode=2)[source]

Read one bit from the slave (instrument).

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

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

Write one bit to the slave (instrument).

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

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

Read multiple bits from the slave (instrument).

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

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • number_of_bits (int): Number of bits to read
  • functioncode (int): Modbus function code. Can be 1 or 2.
Returns:
A list of bit values 0 or 1 (int). 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, values)[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 (int): The slave register start address (use decimal numbers, not hex).
  • values (list of int or bool): 0 or 1, or True or False. The first value in the list is for the bit at the given address.
Returns:
None
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_register(registeraddress, number_of_decimals=0, functioncode=3, signed=False)[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 (int): The slave register address (use decimal numbers, not hex).
  • number_of_decimals (int): The number of decimals for content conversion.
  • functioncode (int): Modbus function code. Can be 3 or 4.
  • signed (bool): 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, value, number_of_decimals=0, functioncode=16, signed=False)[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 (int): The slave register address (use decimal numbers, not hex).
  • value (int or float): The value to store in the slave register (might be scaled before sending).
  • number_of_decimals (int): The number of decimals for content conversion.
  • functioncode (int): Modbus function code. Can be 6 or 16.
  • signed (bool): 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).

Returns:
None
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_long(registeraddress, functioncode=3, signed=False, byteorder=0)[source]

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

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

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • functioncode (int): Modbus function code. Can be 3 or 4.
  • signed (bool): Whether the data should be interpreted as unsigned or signed.
  • byteorder (int): How multi-register data should be interpreted. Defaults to BYTEORDER_BIG.
signed Data type in slave Alternative name Range
False Unsigned INT32 Unsigned long 0 to 4294967295
True INT32 Long -2147483648 to 2147483647
Returns:
The numerical value (int).
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_long(registeraddress, value, signed=False, byteorder=0)[source]

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

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

Uses Modbus function code 16.

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

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • value (int or long): The value to store in the slave.
  • signed (bool): Whether the data should be interpreted as unsigned or signed.
  • byteorder (int): How multi-register data should be interpreted. Defaults to BYTEORDER_BIG.
Returns:
None
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_float(registeraddress, functioncode=3, number_of_registers=2, byteorder=0)[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 (int): The slave register start address (use decimal numbers, not hex).
  • functioncode (int): Modbus function code. Can be 3 or 4.
  • number_of_registers (int): The number of registers allocated for the float. Can be 2 or 4.
  • byteorder (int): How multi-register data should be interpreted. Defaults to BYTEORDER_BIG.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

Type of floating point number 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 (float).
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_float(registeraddress, value, number_of_registers=2, byteorder=0)[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 (int): The slave register start address (use decimal numbers, not hex).
  • value (float or int): The value to store in the slave
  • number_of_registers (int): The number of registers allocated for the float. Can be 2 or 4.
  • byteorder (int): How multi-register data should be interpreted. Defaults to BYTEORDER_BIG.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

Returns:
None
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
read_string(registeraddress, number_of_registers=16, functioncode=3)[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 (int): The slave register start address (use decimal numbers, not hex).
  • number_of_registers (int): The number of registers allocated for the string.
  • functioncode (int): Modbus function code. Can be 3 or 4.

Note

The parameter number_of_registers was named numberOfRegisters before MinimalModbus 1.0

Returns:
The string (str).
Raises:
TypeError, ValueError, ModbusException, serial.SerialException (inherited from IOError)
write_string(registeraddress, textstring, number_of_registers=16)[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 (int): The slave register start address (use decimal numbers, not hex).
  • textstring (str): The string to store in the slave, must be ASCII.
  • number_of_registers (int): 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, number_of_registers, functioncode=3)[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 (int): The slave register start address (use decimal numbers, not hex).
  • number_of_registers (int): The number of registers to read, max 125 registers.
  • functioncode (int): 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 (a list of int). 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, values)[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 (int): The slave register start address (use decimal numbers, not hex).
  • values (list of int): 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.

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

Bases: exceptions.IOError

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.