Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

There is a problem in QserialPort Class.Who can solve it ? Recently, I designed a program based on Windows 10 with using QT5.9.



  • I want to Send a special terminated Command bytes to my MCU board before Closing SerialPort. When i combined send Function into a Push Button Event, actually in a Push Button Slot Fuction, My windows Program does not Send anything and serialPort is Closed at same time.
    I want to send the terminated Command bytes firstly, and the serialport will be closed secondly in the same Slot.
    However, i didnot get the result. Who can help me to solve it? Thank you for your any helps.

    void MainWindow::System_Stop(void)
    {
    bool SerialPort_Status = 0;
    try
    {
    if(SerialPort_Setting_Sucessfully_Flag == 1)
    {
    Stop_Flag = 1;
    SerialPort_Setting_Sucessfully_Flag = 0;
    }
    SerialPort_Status = (char)(serialport1->write((char*)PC_CMD_Stop,10));
    // Serial_Port_Close_Cnt = 0;
    // while(Serial_Port_Close_Cnt < 2);
    serialport1->close();

        if(timer1->isActive())
        {
            timer1->stop();
        }
    
        series0->clear();
        Rx_Fifo.clear();
        Start_Run_Flag = 0;
    }
    catch(QString exception)
    {
        QMessageBox::about(this,"Error",exception);
        Start_Run_Flag = 0;
        SerialPort_Setting_Sucessfully_Flag = 0;
        return;
    }
    

    }



  • SerialPort_Status = (char)(serialport1->write((char*)PC_CMD_Stop,10));
    my_serialport1->waitForBytesWritten();//add this
    serialport1->close();


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Are you using QSerialPort ? If so how are you initializing it ?
    Why are you casting to a char the number of character written ?

    You are closing your port yet in no part of the code you posted are you opening it.



  • Hi, you must wait the char is sended before close the port or try with QSerialPort::flush()



  • @mmiacca That is useful! thanks.



  • or try with QSerialPort::flush()

    No!

    you must wait the char is sended before close

    Yes, it is correct. To do it, you can use bytesWritten() signal and plus some timeout.



  • SerialPort_Status = (char)(serialport1->write((char*)PC_CMD_Stop,10));
    my_serialport1->waitForBytesWritten();//add this
    serialport1->close();


Log in to reply