pikapython/examples/modbus/rtu_master.py

37 lines
1.3 KiB
Python
Raw Normal View History

2023-03-03 00:24:04 +08:00
# Import modbus module
2022-09-19 13:27:20 +08:00
import modbus
2023-03-03 00:24:04 +08:00
# Create a ModBusRTU object, specify the send buffer and receive buffer size as 128 bytes
2023-02-23 15:52:44 +08:00
mb = modbus.ModBusRTU(128, 128)
2023-03-03 00:24:04 +08:00
# Set slave address to 1
2023-02-23 15:52:44 +08:00
mb.setSlave(1)
2022-09-19 13:27:20 +08:00
2023-03-03 00:24:04 +08:00
# Generate a request frame for reading registers, specify the start address as 0 and the quantity as 10
2023-02-23 15:52:44 +08:00
send_buff = mb.serializeReadRegisters(0, 10)
2023-03-03 00:24:04 +08:00
# Print the byte string of the request frame
2022-09-19 14:38:12 +08:00
print(send_buff)
2022-09-19 13:27:20 +08:00
2023-03-03 00:24:04 +08:00
# Parse a response frame for reading registers, return a list containing the values of the registers
2023-02-23 15:52:44 +08:00
host_regists = mb.deserializeReadRegisters(
2022-09-19 13:27:20 +08:00
b'\x01\x03\x14\x00\x00\x00\x00\x04\xD2\x00\x00\x00\x00\x00\x7B\x00\x00\x00\x00\x00\x00\x00\x00\xE5\x0B'
)
2022-09-19 14:38:12 +08:00
print(host_regists)
2022-09-19 13:27:20 +08:00
2022-09-19 14:38:12 +08:00
2023-03-03 00:24:04 +08:00
# Generate a request frame for reading input registers, specify the start address as 0 and the quantity as 2
2023-02-23 15:52:44 +08:00
mb.serializeReadInputRegisters(0, 2)
2023-02-10 11:07:25 +08:00
2023-03-03 00:24:04 +08:00
# Parse a response frame for reading input registers, return a list containing the values of the input registers
2023-02-23 15:52:44 +08:00
mb.deserializeReadInputRegisters(b'\x01\x04\x04\x00\x00\x08\xE6\x7D\xCE')
2023-02-10 11:07:25 +08:00
2023-03-03 00:24:04 +08:00
# Generate a request frame for writing a single register, specify the register address as 0 and the value as 0x1234
2023-02-23 15:52:44 +08:00
send_buff = mb.serializeWriteRegister(0, 0x1234)
print(send_buff)
send_buff = mb.serializeWriteBits(0, [1, 1, 1, 0, 1, 0, 1, 0])
2022-09-19 13:27:20 +08:00
print(send_buff)