最近在实现定时采集气象传感器的数据。在软件实现方面,用PyQt5框架的QTimer实现定时读取传感器信息,但在做测试实验的过程中发现QTimer的精度误差太大,原计划每1秒读一次数据,随着时间的延长,无法实现精确度为1s的读取。
因此在网上找到了解决办法。下面给出python代码以及测试结果。
代码:
from PyQt5.QtCore import QTimer
import datetime as dt
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QThread
class QThreadSensorData(QThread):
def __init__(self):
super().__init__()
self.timerPrin()
def timerPrin(self):
self.timer = QTimer(self)
self.timer.setTimerType(Qt.PreciseTimer) # 关键的一步,取消默认的精度设置
self.timer.timeout.connect(self.printTime) # 打印当前的时间
self.timer.start(1000.00) # 定时为1秒触发
def printTime(self):
print(dt.datetime.now())
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
data = QThreadSensorData()
data.start()
sys.exit(app.exec_())
测试结果:
2020-03-11 22:07:27.401657
2020-03-11 22:07:28.402388
2020-03-11 22:07:29.402548
2020-03-11 22:07:30.402515
2020-03-11 22:07:31.402232
2020-03-11 22:07:32.402093
2020-03-11 22:07:33.402350
2020-03-11 22:07:34.401576
2020-03-11 22:07:35.401716
2020-03-11 22:07:36.401798
2020-03-11 22:07:37.402517
2020-03-11 22:07:38.401717
2020-03-11 22:07:39.401757
2020-03-11 22:07:40.401661
2020-03-11 22:07:41.402510
2020-03-11 22:07:42.402466
2020-03-11 22:07:43.401694
2020-03-11 22:07:44.402286
2020-03-11 22:07:45.401995
2020-03-11 22:07:46.401936
2020-03-11 22:07:47.401721
2020-03-11 22:07:48.401690
2020-03-11 22:07:49.402235
2020-03-11 22:07:50.402019
2020-03-11 22:07:51.402400
2020-03-11 22:07:52.402513
2020-03-11 22:07:53.402245
2020-03-11 22:07:54.401553
2020-03-11 22:07:55.402231
2020-03-11 22:07:56.401617
刚开始的毫秒为:.401,运行29秒后,毫秒为.401,即使在中间出现了.402,通过设置
self.timer.setTimerType(Qt.PreciseTimer)
实现了误差自动补偿,实现了每秒读取数据的功能。
参考资料:
[1]hong_chase,Qt学习笔记-定时器的应用及精度设置, 2017.09, CSDN.