I'm trying to understand why instantiated module variables will not reset after they have been modified once after they are imported. I've been working with minimalmodbus
, and I am trying to reset the Baud rate if the default does not match the connected device's. Setting my own default, I cannot get the re-initialization of of minimalmodbus
to change the baud rate. For example:
import minimalmodbus
minimalmodbus.BAUDRATE=9600
comm=minimalmodbus.Instrument('COM4',1) #baud rate set to 9600 here for comm
minimalmodbus.BAUDRATE=19200
comm=minimalmodbus.Instrument('COM4',1) #attempting to change baud rate
print comm #displays all information, and showing that baudrate=9600, not 19200
I've had this issue using several other modules and I would really like to understand why this is occurring.
The first time you use a given serial port, minimalmodbus
creates a serial.Serial
instance using the current value of BAUDRATE
and saves it :
def __init__(self, port, slaveaddress, mode=MODE_RTU):
if port not in _SERIALPORTS or not _SERIALPORTS[port]:
self.serial = _SERIALPORTS[port] = serial.Serial(port=port, baudrate=BAUDRATE, parity=PARITY, bytesize=BYTESIZE, stopbits=STOPBITS, timeout=TIMEOUT)
else:
self.serial = _SERIALPORTS[port]
if self.serial.port is None:
self.serial.open()
...
Even if BAUDRATE
changes later, future attempts to use that serial port will use the old serial.SERIAL
instance with the old baud rate.
I don't know what the Modbus protocol is like or how you're supposed to use this module, so I can't tell you how you're supposed to do what you're trying to do or whether it's a good idea. In any case, now you know what's happening.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.