I\'m trying to use pyserial to send data to an arduino. But when I open the COM port it sets DTR low and resets the board. However, I have my arduino code setup such that I
Disabling DTR does not work for me:
ser.dtr = None
(Linux 4.4.0 x86_64 / Python 2.7.12 / PySerial 3.4)
But this works:
import serial
import termios
port = '/dev/ttyACM0'
f = open(port)
attrs = termios.tcgetattr(f)
attrs[2] = attrs[2] & ~termios.HUPCL
termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
f.close()
se = serial.Serial()
se.baudrate = 115200
se.port = port
print 'dtr =', se.dtr
se.open()
I found it here.
You ought to be able to disable DTR before opening the port, like this:
com = serial.Serial()
com.port = port
com.baudrate = baud
com.timeout = 1
com.setDTR(False)
com.open()
However, doing so on the current release of pyserial (2.6) on Windows throws the following exception:
..., line 315, in setDTR
ValueError: Attempting to use a port that is already open
This seems to be a bug which is fixed in the latest version of the source, SVN revision 445 on 29th December 2011 (see http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/serial/serialwin32.py?view=log) with comment:
allow setRTS, setDTR before opening on Win32 (to set initial state), doc update
Which looks like it may have just missed the 2.6 release (uploaded on 2nd November 2011 see: https://pypi.python.org/pypi/pyserial).
Furthermore, looking at the current implementation of setDTR()
for POSIX (in serialposix.py) it looks like this bug is not fixed and an exception is thrown if the port is not open, so a cross-platform solution looks unlikely.
The method you describe seems to be the most common fix for this problem that I've seen - so I suspect that there's no simpler software-based solution. You can of course manually change the state of the DTR line using ser.setDTR(level)
- however I haven't tried this specifically in the case of the Arduino autoreset, and I suspect that even toggling the line immediately after opening the serial port may not be fast enough to prevent the reset.
The other options I can see that you have available would be to prevent the autoreset of the Arduino in hardware (see here), or to change your code slightly so that you allow the Arduino to reboot after initially making the serial connection, and then when you manually trigger your serial receive mode send an initial signal from the Arduino to show that it is now ready to receive data. Or alternatively you could include a modified version of the pySerial library with your script.
Here is a software solution, i've been using it myself for a while and it works like a charm:
ser = serial.Serial("/dev/ttyUSB0", 115200, timeout=1)
ser.setDTR(False)
time.sleep(0.5)
Note that the sleep is the tricky part, without it it wont work