Thursday, October 17, 2013

Fun with QSerialPort

Fun with QSerialPort


As we know, we can use QSeialPort to communicate with devices via RS232/RS485 or via virtual COM ports (I recommend to use devices based on MCP2200 not on FT232, because they are cheaper :) )

Many years ago I used a PComm.dll (as I know, it developed by MOXA) to work with COM ports from my applications written in C++/Delphi (in Windows). Later I found QSerialDevice library for Qt. But now, as I told before, we can use QSerialPort directly from Qt version 5.1 and higher.



But when I tried to use it in Windows (Win 7 x64 and Qt 5.1.1 x32) I found extremely strange bug: when I tried to communicate with serial device (using QSerialPort) I could not read any data from port, before I will try to read/write using Hyper Terminal or any other software. Very strange, is't it? So, after each reboot of OS I have to use HT (or something like this) and only after that my application (which uses QSerialPort) will start to work. Very stupid and strange.

But it can be easily fixed.

My old code was:

m_Port = new QSerialPort;

m_Port->setPortName(QLatin1String("COM6"));
m_Port->setBaudRate(QSerialPort::Baud9600);
m_Port->setDataBits(QSerialPort::Data8);
m_Port->setStopBits(QSerialPort::OneStop);
m_Port->setParity(QSerialPort::NoParity);
m_Port->setFlowControl(QSerialPort::NoFlowControl);


bool ok = m_Port->open(QIODevice::ReadWrite);

but correct code is:

m_Port = new QSerialPort;

m_Port->setPortName(QLatin1String("COM6"));
bool ok = m_Port->open(QIODevice::ReadWrite);


if(!ok)
  return false;

m_Port->setBaudRate(QSerialPort::Baud9600);
m_Port->setDataBits(QSerialPort::Data8);
m_Port->setStopBits(QSerialPort::OneStop);
m_Port->setParity(QSerialPort::NoParity);

m_Port->setFlowControl(QSerialPort::NoFlowControl);


So, main goal is to OPEN PORT AND ONLY THEN CONFIGURE IT. Otherwise your code will work a little bit strange :)

Hope it was useful.

UPD: Qt documentation says


Having successfully opened, QSerialPort tries to determine the current configuration of the port and initializes itself. You can reconfigure the port to the desired setting using the setBaudRate(), setDataBits(), setParity(), setStopBits(), and setFlowControl() methods.

So it's not a bug it's a feature.

No comments:

Post a Comment