I had the same problem with arduino leonardo.
I want to share my solution for people wanting to solve this problem using Qt.
Here is solution ready to be copy and paste, also taking care of timeout:
#include <QtCore/QString>
#include <QtCore/QDebug>
#include <QtCore/QThread>
#include <QtCore/QElapsedTimer>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
bool forceResetComPort(const QString& portName)
{
QSerialPort serial;
serial.setPortName(portName);
serial.setBaudRate(1200);
qDebug() << "Forcing reset using 1200bps open/close on port ") << portName;
if(!serial.open(QIODevice::ReadWrite))
return false;
// This seems optional
serial.setDataTerminalReady(false);
qDebug() << "Waiting for the new upload port...";
QElapsedTimer timeoutWatcher;
qint64 timeoutMs = 10000;
bool isPortPresent = true;
const auto fetchIsPortPresent = [&]() -> bool
{
const auto ports = QSerialPortInfo::availablePorts();
for(const auto& info : ports)
{
if(info.portName() == serial.portName())
return true;
}
return false;
};
timeoutWatcher.start();
// Wait for port to disconnect
while(isPortPresent && !timeoutWatcher.hasExpired(timeoutMs))
{
isPortPresent = fetchIsPortPresent();
if(isPortPresent)
QThread::msleep(1);
}
serial.close();
// Wait for port to reconnect
while(!isPortPresent && !timeoutWatcher.hasExpired(timeoutMs))
{
isPortPresent = fetchIsPortPresent();
if(!isPortPresent)
QThread::msleep(1);
}
return !timeoutWatcher.hasExpired(timeoutMs);
}
It is all about timing. I really needed to wait for the serial port to disconnect to close serial.
- Closing too fast didn't have any effect.
- Closing too slow, the usb serial was reconnecting but with a different port name. (For example /dev/ttyACM0 to /dev/ttyACM1).
- It's important to wait for the port to reconnect in my case because I call avrdude in QProcess after.
Here is dmesg:
[ 8566.623621] cdc_acm 1-8:1.0: failed to set dtr/rts
[ 8566.979697] usb 1-8: new full-speed USB device number 21 using xhci_hcd
[ 8567.133193] usb 1-8: New USB device found, idVendor=2341, idProduct=0036, bcdDevice= 0.01
[ 8567.133197] usb 1-8: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[ 8567.133199] usb 1-8: Product: Arduino Leonardo
[ 8567.133200] usb 1-8: Manufacturer: Arduino LLC
[ 8567.134820] cdc_acm 1-8:1.0: ttyACM0: USB ACM device