Article 5HE9E Python: suppressing DTR when opening serial port

Python: suppressing DTR when opening serial port

by
Wim Sturkenboom
from LinuxQuestions.org on (#5HE9E)
Good day

I'm using Arduino for embedded applications and communicate over serial ports (e.g. ttyUSB0). With a number of Arduinos, the problem is that they reset when the serial port is opened because DTR is asserted; this is by design.

First attempts to suppress DTR were not quite successful but with some googling I got to below code; the only problem is that the very first time that the serial port is opened, DTR is still asserted.

How do I modify the below code that this does not happen? A link to some web page will be fine, modified code as well ;)

Thanks in advance

Code:import sys
import serial
import termios

# print some python info for fun
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)

# define the port
port = '/dev/ttyUSB0'
resetPort = False

if resetPort == False:
# to be able to suppress DTR, we need this
f = open(port)
attrs = termios.tcgetattr(f)
attrs[2] = attrs[2] & ~termios.HUPCL
termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
f.close()
else:
f = open(port)
attrs = termios.tcgetattr(f)
attrs[2] = attrs[2] | termios.HUPCL
termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
f.close()

with serial.Serial() as ser:
# setup serial port
ser.baudrate = 57600
ser.port = port
ser.rtscts = False # not setting to false prevents communication
ser.dsrdtr = resetPort # determines if Arduino resets or not
ser.timeout = 2

# print settings
print (ser.name)
print (ser)

# open serial port
ser.open()

# read initial Arduino message
s = ser.read(20)
print(s)

# send some data to be echoed
# b is needed for python3
ser.write(b'hello world')
s = ser.read(20)
print(s)

ser.close
print('done')Notes:
  1. If I understand man pages correctly, the same problem will occur in C/C++ programs.
  2. I'm absolutely green when it comes to Python
  3. I've written similar code in C# (Windows) which successfully suppresses DTR when the serial port is opened
latest?d=yIl2AUoC8zA latest?i=yeqpXy7HBdM:zRIqvmlPzn0:F7zBnMy latest?i=yeqpXy7HBdM:zRIqvmlPzn0:V_sGLiP latest?d=qj6IDK7rITs latest?i=yeqpXy7HBdM:zRIqvmlPzn0:gIN9vFwyeqpXy7HBdM
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments