Delay between serial messages sent by QSerialPort



  • I am sending messages via RS232 / serial port from my QT desktop application to an embedded controller. The embedded controller has limited resources and cannot process two messages quickly enough before one message overwrites the other in the buffer. I would like to implement a delay between messages. Using QThread::quiet(2000) between serialport->write calls does not seem to have any impact on the timing of the messages; I can see on the oscilloscope that they get sent at the same time.

    Can anyone please suggest a method to enter a delay between the writing of messages out of the serial port?



  •  class MessagesSender : public QObject
     {
        Q_OBJECT
     public:
        explicit MessagesSender(QObject *parent = 0)
            : QObject(parent)
        {
            outgoingTimer = mew QTimer(this);
            outgoingTimer->setSingleShot(true);
            outgoingTimer->setInterval(2000);
            connect(outgoingTimer, SIGNAL(timeout()), this, SLOT(writeOutgoingMessage()));
        }
    
        void writeMessage(const QByteArray &message)
        {
            outgoingMessages.append(message);
            if (!outgoingTimer->isActive())
                outgoingTimer->start();
        }
    
     private slots:
        void writeOutgoingMessage()
        {
            if (outgoingMessages.isEmpty)
                return;
            const QByteArray message = outgoingMessages.takeFirst();
            outgoingInterface->write(message);
            outgoingTimer->start();
        }
    
     private:
        QSerialPort *outgoingInterface;
        QTimer *outgoingTimer
        QList<QByteArray> outgoingMessages;
     }
    


  • Thank you for the idea. Yes, writing a wrapper class around the serial port worked like a charm. I implemented it a bit differently, a message handler manages the message building and sending it off to the serial port but the concept is the same. The only thing I found different from your example is that the timer isn't destroyed when it runs out. Instead of creating a new one every time, I created one as part of the class and use it over and over again.

    Thank you very much for the insight!!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.