Connor Spangler
Connor Spangler

Reputation: 815

How to only send DTR/RTS signal on port open but not port close via pySerial

I have a system which, when its COM port is opened or closed via pySerial, receives reset signals on both which is nominal behavior:

with Serial("COM4", 19200) as ser:
    ser.write(bytearray[89])

What I want to have happen however is for the reset to only occur on port open, and to allow the system to continue running on port close.

My unsuccessful attempt:

ser = serial_for_url("COM4", 19200, do_not_open=True)
ser.dtr = 0
ser.rts = 0
ser.open()

ser.write(bytearray[89])

ser.dtr = 1
ser.rts = 1
ser.close()

Is this possible? Or are the nature of posix ports such that their behavior is fixed at instantiation?

Thank you!

Upvotes: 0

Views: 2525

Answers (1)

kunif
kunif

Reputation: 4350

Whether or not they can be done depends on the operating system and device drivers.
Then, the setting value of rts,dtr will be True,False instead of 1,0.

pySerial API

open()
Open port. The state of rts and dtr is applied.

Some OS and/or drivers may activate RTS and or DTR automatically, as soon as the port is opened. There may be a glitch on RTS/DTR when rts or dtr are set differently from their default value (True / active).

For compatibility reasons, no error is reported when applying rts or dtr fails on POSIX due to EINVAL (22) or ENOTTY (25).

rts
Setter: Set the state of the RTS line
Getter: Return the state of the RTS line
Type: bool

Set RTS line to specified logic level. It is possible to assign this value before opening the serial port, then the value is applied upon open() (with restrictions, see open()).

dtr
Setter: Set the state of the DTR line
Getter: Return the state of the DTR line
Type: bool

Set DTR line to specified logic level. It is possible to assign this value before opening the serial port, then the value is applied upon open() (with restrictions, see open()).


If your system supports the features, could your program be modified as follows?
Please try it.

ser = serial_for_url("COM4", 19200, do_not_open=True)
ser.dtr = False
ser.rts = False
ser.open()
time.sleep(0.1) # The time required for the device to recognize the reset condition.
ser.dtr = True
ser.rts = True
time.sleep(2.0) # The time required for the device to complete the reset operation.

ser.write(bytearray[89])

ser.flush() # wait until all data is written.
ser.close()

Upvotes: 2

Related Questions