Qt Serial Port

I am writing a Qt application to communicate with another computer through a serial port. I have 2 real questions.

1. I can send and receive data in order, but sometimes the serial port β€œeats” part of my input. For example, if I send:

cd /application/bin 

sometimes (not always) he will receive only:

 cd /applica 

(Since it is a terminal, it repeats the entry back. Also, my invitation tells me that I am clearly in the wrong place.)

2. In addition, sometimes the Qt slot, which fires when there is available data, does not fire, although I know that there is data that I can get. If I send another \r\n down the port, the slot will be lit. For example, sometimes I ls something and the command name will be read back from the port, but the contents of the folder are sitting there in limbo until I return again. Then I get a list of directories and two requests.

Here is my code:

 void Logic::onReadyRead(){ QByteArray incomingData; incomingData = port->readAll(); QString s(incomingData); emit dataAvailable(s);// this is a Qt slot if you don't know what it is. qDebug() << "in:"<< s.toLatin1(); } void Logic::writeToTerminal(QString string ) { string.append( "\r\n"); port->write((char*)string.data(), string.length()); if ( port->bytesToWrite() > 0){ port->flush(); } qDebug() << "out:" << string.toLatin1(); } 
+4
source share
2 answers

I found a solution, and I suspect this is a coding error, but I'm not sure. Instead of sending a QString over a serial port, sending a QByteArray fixed both problems. I changed the writeToTerminal() method:

 void Logic::writeToTerminal(QString string ) { string.append( "\r"); QByteArray ba = string.toAscii(); port->write(ba); } 
+2
source

From this forum , it seems that sometimes not all data is sent, and everything that is sent has the added '\ 0' This. Therefore, if

cd / applica '\ 0' is sent, then port->readAll() will stop there because it thinks it has read everything.

One of the suggested answers on this forum was to read line by line, which your code almost does. Therefore, I think that in your case you can change your code to:

 void Logic::onReadyRead(){ QByteArray incomingData; if(port->canReadLine()) { incomingData = port->readLine(); QString s(incomingData); emit dataAvailable(s);// this is a Qt slot if you don't know what it is. qDebug() << "in:"<< s.toLatin1(); } } void Logic::writeToTerminal(QString string ) { string.append( "\r\n"); port->write((char*)string.data(), string.length()); if ( port->bytesToWrite() > 0){ port->flush(); } qDebug() << "out:" << string.toLatin1(); } 
0
source

Source: https://habr.com/ru/post/1495045/


All Articles