SHARE
TWEET

Workaround

a guest Jan 15th, 2018 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <QCoreApplication>
  2. #include <QTimer>
  3. #include <QtGlobal>
  4. #include <QSerialPort>
  5. #include <QSerialPortInfo>
  6. #include <QDateTime>
  7.  
  8. #include <thread>
  9.  
  10.  
  11. typedef enum {
  12.     SUCCESS,
  13.     ERROR
  14. } ErrorCode;
  15.  
  16. // Initialize QCoreApplication and quit after 11 seconds
  17. void initQCoreApplication(int argc, char* argv[])
  18. {
  19.     QCoreApplication app(argc, argv);
  20.     QTimer::singleShot(11000, &QCoreApplication::quit);
  21.     app.exec();
  22. }
  23.  
  24. // Read serial port for 10 seconds and print data
  25. void readPort(QSerialPort* port)
  26. {
  27.     for(qint64 startTime = QDateTime::currentSecsSinceEpoch()+10;QDateTime::currentSecsSinceEpoch() < startTime;)
  28.     {
  29.         if(port->waitForReadyRead(100))
  30.         {
  31.             qInfo("Read data %s", port->readAll().constData());
  32.         }
  33.     }
  34. }
  35.  
  36. int main(int argc, char* argv[])
  37. {
  38.     std::thread appThread(initQCoreApplication, argc, argv);
  39.  
  40.     QSerialPort port("COM10");
  41.     if(!port.open(QIODevice::ReadOnly))
  42.     {
  43.         return ERROR;
  44.     }
  45.  
  46.     // Make sure that QCoreApplication has been instantiated
  47.     while(QCoreApplication::startingUp())
  48.     {
  49.         std::this_thread::sleep_for(std::chrono::milliseconds(100));
  50.     }
  51.     // Moving the object to the applications thread is crucial
  52.     port.moveToThread(QCoreApplication::instance()->thread());
  53.  
  54.     std::thread thread(readPort, &port);
  55.     thread.join();
  56.  
  57.     appThread.join();
  58.     port.close();
  59.  
  60.     return SUCCESS;
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top