wait for data arrive from serial port in Qt

后端 未结 1 1866
醉酒成梦
醉酒成梦 2020-12-22 10:55

I use serial port connection in my qt application. My problem- I cant get back the control (or the values comes from the comm port) after sending the command.

I have

相关标签:
1条回答
  • 2020-12-22 11:34

    The QSerialPort class inherits from QIODevice which has waitFor... methods that may be what you're looking for. Take a look at these docs.

    If you want to handle the serial port asynchronously, use the readyRead signal and perform reading in a function that you connected to that signal. If you don't mind that the operation is blocking, the waitForReadyRead function is what you're looking for.

    The good way

    Here's the proper way to do it using Qt's signals and slots mechanism. This will not block your GUI and lets your application respond to user actions even while you are waiting for the serial port.

    1. Connect a function to the bytesWritten signal
      The code you want to execute after you sent data through the serial port should be placed in this function.
    2. Connect a function to the readyRead signal The code you want to execute after you read some data from the serial port should be placed in this function.
    3. Open the port

    The bad way

    In some cases you can do it like this, but it's blocking, meaning that your GUI will freeze while your app is waiting for the serial port. I don't recommend doing it like this.

    1. Open the port
    2. Send data
    3. Call waitForBytesWritten
    4. Call waitForReadyRead

    Working example code

    Qt has a vast amount of working example code. There are even examples about how to use QSerialPort, and they are well worth checking out. You might be most interested in the async writer example and the async reader example.

    0 讨论(0)
提交回复
热议问题