用Python透過Modbus通訊規格,讀取溫度控制器的溫度讀值

需安裝的套件:

  1. minimalmodbus
    安裝語法: pip install minimalmodbus
    因為minimalmodbus要依賴pyserial才能運作,所以安裝minimalmodbus就會自動把pyserial也一併安裝進去
  2. pyserial
    安裝語法: pip install pyserial

硬體接線

通訊參數

Baud rate: 9600
Length: 7 bit
Parity: Even
Stop bit: 1

來看程式吧~

import serial
import minimalmodbus

instrument = minimalmodbus.Instrument(port='COM3', slaveaddress=1)  # port name, slave address (in decimal)
instrument.serial.baudrate = 9600
instrument.serial.bytesize = 7
instrument.serial.parity   = serial.PARITY_EVEN
instrument.serial.stopbits = 1
instrument.serial.timeout  = 1          # seconds
instrument.mode = minimalmodbus.MODE_ASCII
instrument.clear_buffers_before_each_transaction = True
## Read temperature (PV = ProcessValue) ##
temperature = instrument.read_register(int("4700", 16), 1)  # Registernumber, number of decimals
print(temperature)

順利讀到溫度: 31.4

2個讚