QTimer in Threads Emits Time out at Wrong Timing



  • The idea is to achieve serial communication using multi-threading at every 10ms.
    Platform used: Linux, Python and Pyqt for UI, PySerial for Serial Communication.

    Thread creation code snippet is given below:

      self.objThread[i] = QThread()  
    

    Starting Timer in Thread class, as shown below:

    self.ctimer = QTimer() 
    self.ctimer.timeout.connect(self.readWriteData) 
    self.ctimer.start(self.TIME_INTERVAL)
    

    In TimeOut slot, just calling Transmit and Receive Routine

    def readWriteData(self): 
         print("Time = ",datetime.now().strftime('%d:%m:%Y_%H:%M:%S.%f')[:-3]) 
         if(temp_packet_rate != 'aperiodic'):
             if(self.serial_operation_flag[self.index] == 1):      
                if(self.Transfer_direction == 'T'):
                   self.Transmit_Routine()
                elif(self.Transfer_direction == 'R'):   
                   self.Receive_Routine()
    

    In above Routine, Printing Time. Could make out that the above routine is called beyond 10ms, something like 11, 12.. some times more than 30ms.

    Obersvation:
    In transmit Routine, when the Data is put on serial Out buffer, it takes more time, here is the routine

    ser_handler[index].write(transmit_data_edited.encode())
    

    Serial Handler is initiated with all details like, Port name, Baud Rate, Parity and Stop bit. Time out is set to 0.

    Please suggest me where the mistake could be. How could 10ms timing can be acheived

    Thanks in advance


  • Lifetime Qt Champion

    Hi,

    You have to ensure that everything you do in readWriteData takes less than 10ms including your print statement.



  • @SGaist yes.. print statement takes more time.. so printing timing into a file, after each step. also when i disable writing data into serial buffer, timing is fine. But once enebled that, found that Qtimer goes for toss



  • Using QTimer for precise timing is conceptually not a good idea.
    see QTimer docs :

    "All timer types may time out later than expected if the system is busy or unable to provide the requested accuracy"

    regards
    Karl-Heinz



  • @Dayama-Pradeep
    You can also start a QElapsedTimer at the beginning of readWriteData substract that from your 10 ms and start the Time new with the modified time.

    Should reduce the shift.





  • @J.Hilk will look into it and revert back.. thanks for suggestion


Log in to reply
 

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