Unsolved Reading from serial port
-
Hello.
I use next code to communicate with some hadware by UART.
I send commands:void controller::sendCommand(QString command) { serialPort.write(command.toUtf8()); serialPort.waitForBytesWritten(100); }
and controller returns answer asynchronously. I process it next way:
connect(&serialPort, &QSerialPort::readyRead, this, &controller::processReadyRead); void controller::processReadyRead() { QByteArray messageData; while (serialPort.waitForReadyRead(100)) { messageData += serialPort.readAll(); } // process data }
for example, for success controller returns "OK!" string.
But answer comes in strange way: sometemes i got "OK!", sometemes i got "" (empty string) and after next command got "OK!OK!" (answer for this and prev command).
what is right way to get answers correctly (one for each command)? -
Hi,
Do not mix the blocking and asynchronous APIs. Send your command and once you got the full "OK!" frame, send the following command.
-
Do not mix the blocking and asynchronous APIs.
can you explain, please?
Send your command and once you got the full "OK!" frame, send the following command.
getting some responses in one message is not a problem, i use number to mark commands and answers. But can you explain why it do such way?
And why i get empty responses? its a problem.
One more thing: sometimes controller generate status messages and sends it to me without command from my side. -
@gogoer In simple words: Don't use the waitForXXX methods as they block the eventloop and hence the signals. Instead of using those methods then just use the signals. It also eliminates the whiles since if they run for a long time they also block the eventloop. Also provide a minimal and reproducible example.