Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <QCoreApplication>
- #include <QTimer>
- #include <QtGlobal>
- #include <QSerialPort>
- #include <QSerialPortInfo>
- #include <QDateTime>
- #include <thread>
- typedef enum {
- SUCCESS,
- ERROR
- } ErrorCode;
- // Initialize QCoreApplication and quit after 11 seconds
- void initQCoreApplication(int argc, char* argv[])
- {
- QCoreApplication app(argc, argv);
- QTimer::singleShot(11000, &QCoreApplication::quit);
- app.exec();
- }
- // Read serial port for 10 seconds and print data
- void readPort(QSerialPort* port)
- {
- for(qint64 startTime = QDateTime::currentSecsSinceEpoch()+10;QDateTime::currentSecsSinceEpoch() < startTime;)
- {
- if(port->waitForReadyRead(100))
- {
- qInfo("Read data %s", port->readAll().constData());
- }
- }
- }
- int main(int argc, char* argv[])
- {
- std::thread appThread(initQCoreApplication, argc, argv);
- QSerialPort port("COM10");
- if(!port.open(QIODevice::ReadOnly))
- {
- return ERROR;
- }
- // Make sure that QCoreApplication has been instantiated
- while(QCoreApplication::startingUp())
- {
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
- }
- // Moving the object to the applications thread is crucial
- port.moveToThread(QCoreApplication::instance()->thread());
- std::thread thread(readPort, &port);
- thread.join();
- appThread.join();
- port.close();
- return SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement