Timing issues: QT write to serial port followed by read
<p>I'm making a Qt data acquisition GUI to replace LabVIEW for an application in my lab.</p>

<p>I want a pushbutton on my GUI to write some data to the serial port (to a microcontroller), then wait for data acquisition to finish (which the microcontroller does) and then get the data back over the serial port for saving, plotting, etc.</p>

<p>The following void checks for incoming serial data.  It prints the number of bytes in the serial buffer.</p>

<p>Now, when I run the program I click the button and get "0" on the first click.  A second click gives me the correct number of bytes available.  </p>

<p>It appears that I am not getting the incoming serial data available until the next time I click the pushbutton.  Why is this?</p>

<pre><code>void MainWindow::on_run_PushButton_clicked(){

sendserialData("go");

quint64 availablebytes = 0; 
int i=0;
while(availablebytes &lt; 4 ){ // less than 4 bytes on the incoming serial buffer
    availablebytes = microcontroller-&gt;bytesAvailable();
    qDebug() &lt;&lt; availablebytes;
    i++;
    if(i==4){break;}
}
</code></pre>

<p>FYI if it is important, here are the properties of the serial port:</p>

<pre><code>if(microcontroller_is_available){
   // open and configure serialport
    microcontroller-&gt;setPortName(microcontroller_port_name);
    microcontroller-&gt;open(QSerialPort::ReadWrite);
    microcontroller-&gt;setBaudRate(QSerialPort::Baud115200);
    microcontroller-&gt;setDataBits(QSerialPort::Data8);
    microcontroller-&gt;setParity(QSerialPort::NoParity);
    microcontroller-&gt;setStopBits(QSerialPort::OneStop);
    microcontroller-&gt;setFlowControl(QSerialPort::NoFlowControl);

}
else{
    QMessageBox::warning(this, "Port error", "Cannot connect to the microcontroller.");
}
</code></pre>

<p>UPDATE 14 Nov 2016</p>

<p>Following the suggestions of others, the following code works properly, reading in the data immediately once I have pushed the pushbutton.  I connected the readyRead signal to readData:</p>

<pre><code>connect(microcontroller, &amp;QSerialPort::readyRead, this, &amp;MainWindow::readData);

void MainWindow::on_run_PushButton_clicked()
{
ui-&gt;run_PushButton-&gt;blockSignals(true);
serialData="";
sendserialData("go");
}

void MainWindow::sendserialData(QString command)
{
if(microcontroller-&gt;isWritable()){
    microcontroller-&gt;write(command.toStdString().c_str());
}else{
    qDebug() &lt;&lt; "Cannot write to the microcontroller";
}
}

void MainWindow::readData()
{
serialData += microcontroller-&gt;readAll();
qDebug() &lt;&lt; serialData;
ui-&gt;run_PushButton-&gt;blockSignals(false);
}
</code></pre>

<p>Note the use of blockSignals, so the DAQ cannot be started while it is already running.</p>