目次

Modbus のプログラミング (pylibmodbus)

libmodbus の Python binding “pylibmodbus”1)を利用し、簡単に Modbus 機器と通信するプログラムを作ることができます。


使用方法

ipython3 でインタラクティブに試すことができます。
実行例を下記に示します。

root@plum:~# ipython3 
Python 3.4.3 (default, Oct 14 2015, 21:23:51) 
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import pylibmodbus

In [2]: pylibmodbus.ModbusRtu?
Type:       type
String Form:<class 'pylibmodbus.modbus_rtu.ModbusRtu'>
File:       /usr/lib/python3/dist-packages/pylibmodbus/modbus_rtu.py
Docstring:  <no docstring>
Constructor information:
 Definition:pylibmodbus.ModbusRtu(self, device='/dev/ttyS0', baud=19200, parity='N', data_bit=8, stop_bit=1)

In [3]: rtu=pylibmodbus.ModbusRtu('/dev/ttyUSB0', baud=19200)

In [4]: rtu.connect()

In [5]: rtu.set_slave(1)

n [6]: rtu.read_input_bit(0)
Out[6]: 1


API

libmodbus の API Reference は、ここ にあります。
Python の API もほぼ同じ内容となっています。一部、使いやすいようメソッドを追加しています。


Python Arguments libmodbus function Note
Context
ModbusRtuコンストラクタdevice=“/dev/ttyS0”, baud=19200, parity=“N”, data_bit=8, stop_bit=1modbus_new_rtuCreate a libmodbus context for RTU
Connection
connect modbus_connectEstablish a connection
clonse modbus_closeClose a connection
Common
set_slave slavemodbus_set_slaveSet slave ID
Client (Read data)
read_bits addr, nbmodbus_read_bitsModbus function code 0x01 (read coil status)
read_bit addr
read_input_bits addr, nbmodbus_read_input_bitsModbus function code 0x02 (read input status)
read_input_bit addr
read_registers addr, nbmodbus_read_registersModbus function code 0x03 (read holding registers)
read_input_registers addr, nbmodbus_read_input_registersModbus function code 0x04 (read input registers)
Client (Write data)
write_bit addr, statusmodbus_write_bitModbus function code 0x05 (force single coil)
write_register addr, valuemodbus_write_registerModbus function code 0x06 (preset single register)
write_bits addr, nb, datamodbus_write_bitsModbus function code 0x0F (force multiple coils)
write_registers addr, datamodbus_write_registersModbus function code 0x10 (preset multiple registers)
Client (Write and Read)
write_and_read_registers write_addr, data, read_addr, read_nbmodbus_write_and_read_registersModbus function code 0x17 (write/read registers)
Timeout
set_response_timeout secondsmodbus_set_response_timeoutset the timeout interval used to wait for a response
get_response_timeout modbus_get_response_timeoutreturn the timeout interval used to wait for a response


1)
v2.6.6α1 からインストールしています