Unsolved Problem with QSerialPort
-
My problem is the following, I have two slot functions connected to a QPushButton that make the connection and disconnect to an arduino . And in the connection function I show a message on a display that arduino is already connected to the PC and in the other function show a message on the display when I disconnect. Then I show the functions A and B, I have reviewed and the problem I have is that the signal does not send the arduino, in the case of the connection function if I do a slot function where it has only arduino -> write(code), the message is received by the arduino. And in the case of disconnection if I remove the function close () I get the message displayed on the display.
Why is the message not sent to the arduino when I send it through the slot functions A and B?How can I correct these functions?
Thanks for help me.A)
void Widget::connectToArduino()
{
if(arduino_is_available){
// open and configure the serialport
arduino->setPortName(selectedPort);
arduino->open(QSerialPort::WriteOnly);
arduino->setBaudRate(QSerialPort::Baud9600);
arduino->setDataBits(QSerialPort:ata8);
arduino->setParity(QSerialPort::NoParity);
arduino->setStopBits(QSerialPort::OneStop);
arduino->setFlowControl(QSerialPort::NoFlowControl);arduino->write("#STAR\n");//Code to show message of connection to the pc.
connectButton->setText("Disconnect");
enableControls();
}else{
// give error message if not available
QMessageBox::warning(this, "Port error", "Couldn't find the Arduino!");
}
}B)
void Widget::disconnectFromArduino()
{
arduino_is_available = false;
arduino_port_name="";
selectedPort="";
resetDefaults();
if(arduino->isWritable())
{
qDebug() << "Is writable";
arduino->write("#STOP\n");
}
closePort();
this->repaint();
}
void Widget::closePort()
{
portList.clear();
PortComboBox->clear();
//delete arduino;
arduino->close();
} -
@albert-huert Hi,
When you write to serial port there is a delay before the data are really written on the hardware. So as you close the port after you have written it is probably closed before the data have been sent. You can add
QIODevice::waitForBytesWritten()
to wait until writing has been finished. You can also use the signalQIODevice::bytesWritten()
to avoid blocking the GUI. But I don't think that's so critical here as it should be few milliseconds, except if there is an IO error.