I am performing an app with QT for communicate my PC with an 8 bits microcontroller through rs-232. I am using the QtSerialPort library and the communication is working fine, but each time I write something from the PC to the micro and I receive the response, I have to close and open the serial port or I can't continue communicating.. My configuration is: 10500 bps, 8 bits, 1 stop, no parity, no flow control.
The code used for the configuration and the lecture/writting of the port is the next:
bool DriverS::configure(int port, int baudRate)
{
if(port!=22)
return false;
serialPort->setPortName("COM22");
if (serialPort->open(QIODevice::ReadWrite)==true){
if (!serialPort->setBaudRate(baudRate)) {
return false ;
}
if (!serialPort->setDataBits(QSerialPort::Data8)) {
return false ;
}
if (!serialPort->setParity(QSerialPort::NoParity)) {
return false;
}
if (!serialPort->setStopBits(QSerialPort::OneStop)) {
return false;
}
if (!serialPort->setFlowControl(QSerialPort::NoFlowControl)){
return false;
}
};
return true;
}
bool DriverS::read(QByteArray & rxData, int * size)
{
Sleep(200);
*size = 0;
if (serialPort->waitForReadyRead(TIMEOUT_SERIAL)) {
rxData = serialPort->readAll();
*size = rxData.size() ;
if (!this->checkCRC(rxData))
{
qDebug()<< "Rx Checksum Error";
return false;
}
return true;
}
qDebug()<< "Rx Timeout";
return false;
}
bool DriverS::write(QByteArray txData)
{
unsigned int chk = 0;
int ret ;
for(int i = 0;i<txData.size();i++)
{
chk+=txData.at(i);
}
txData.append(chk);
ret = serialPort->write(txData);
return (txData.size()==ret);
}
I just found myself with exactly the same situation. I was getting stuck in the read routine. Try opening the port in unbuffered mode.
port->open(QIODevice::ReadWrite | QIODevice::Unbuffered)
It was just on one computer I found this, I've never had to do it before, but it might get you out of a hole.
I fixed my two problems (despite I am not sure about the methods).
For problem num 1 (open and close the port each time I wanted to communicate) I just added a waitFoBytesWritten() in my write method.
For my problem num 2, (I only was able to work with port22), I have modified the configuration and now I first detect wich ports are available with availablePorts() instead to force the port I want to use. Now I can connect my device to any free port and it works..