Unable to communicate with arduino using QSerialPort if the arduino-ide has not opened the connection before

StackOverflow https://stackoverflow.com/questions/23198241

Question

I am using the following code to open a serial port to communicate with the arduino.

  const qint32 baud = Global::getInstance().getSettings().value("Hardware/baudRate", 115200).toInt();
  const QString portName = Global::getInstance().getSettings().value("Hardware/port", "COM3").toString();
  port.setPortName(portName);

  if(!port.open(QIODevice::ReadWrite))
  {
    qFatal("Unable to open serial port");
    exit(1); 
  }
  if(!port.setParity(QSerialPort::NoParity) ||
     !port.setStopBits(QSerialPort::OneStop) ||
     !port.setDataBits(QSerialPort::Data8) ||
     !port.setFlowControl(QSerialPort::NoFlowControl ) ||
     !port.setBaudRate(baud))
  {
     qFatal("Unable to configure serial port");
     exit(1); 
  }
  if(port.error() != QSerialPort::NoError)
  {
    qFatal("some error occurred!");
    exit(1);
  }

Afterwards I try to read from the connection using the following code:

bool Light::waitForReady()
{
  char data[1];
  data[0] = -1;
  if(port.waitForReadyRead(10000))
  {
    const int numRead = port.read(&data[0], 1);
    if(numRead == 1)
    {
      return data[0] == (char)RDY;
    }
    else
    {
      qWarning("Read error, read %d bytes", numRead);
    }
  }
  else
  {
    qWarning("Read timeout");
    return false;
  }
  return false;
}

The read does not work, it times out after waiting for 10 seconds. However when I open and close the serial monitor inside the arduino-ide before running my QT code it works. My guess is that the ardunio-ide does something to the port that I am missing but as far as I can tell I am using the exact same settings as the arduino-ide to open the serial port.

This is the code that is running on the arduino:

void setup() 
{
  Serial.begin(115200);
  Serial.write(RDY);
}

This guy has had a similar problem and he compared the serial port settings of putty and QSerialPort. He found that the settings fDtrControl, fOutX and fIutX differed. I tried changing fDtrControl but it had no effect. I do not know how to set fOutX and fIutX using QT.

Any ideas what might be causing this bug?

edit: Solution: port.setDataTerminalReady(true) was missing

Was it helpful?

Solution

I do not know how to set fOutX and fIutX using QT.

Please read my answer is in here.

Also be convinced that the Putty (or your arduino-terminal) configuration (parity, flow control, baud rate) are same as QSerialPort configuration. In addition, you can try the Terminal example (from the QtSerialPort examples), e.g. instead of Putty (or your arduino-terminal).

UPD:

You can try to add:

setDataTerminalReady(true);

and

setRequestToSend(true);

after opening of port.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top