1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PyQt5をつかってPythonで周期処理

Last updated at Posted at 2019-01-06

ロボット的な何かを作るときとか、できるだけ正確にタイマー割り込みを行って周期処理をしたいじゃないですか。
Pythonのこの手の処理、ググるとスレッド使ったりOSのシステムコール使ったりといろいろあれどWidnowsでもラズパイでも同じコードでms単位で正確に動くやつってなくて、Qtに頼るやつだと動きそうな雰囲気なので忘備録としてまとめました。

主に以下の記事を参考にしました。
https://www.valuestar.work/news/archives/92

QtのsetInterval()を使っています。
時と場合によってライセンスには注意が必要ですが、PyQt5が入っていればWindowsでもRapbianでも同じコードで動くから便利。

import sys
from PyQt5.QtCore import *
import time

prevTime = 0

def main():
    app =  QCoreApplication(sys.argv)
    t1 = QTimer()
    t1.setInterval(10) #割り込み周期をms単位で指定
    t1.timeout.connect(TimerTest) #実行する関数を指定
    t1.start()
    sys.exit(app.exec_())

def TimerTest(): #実行される関数
	global prevTime
	currentTime = time.time()
	print(currentTime - prevTime)
	prevTime = currentTime

if __name__ == '__main__':
	prevTime = time.time()
	main()

10msごとにTimerTest()が実行されることを意図しています。
TimerTest()では前回実行された時間からどれくらい立っているか計測しています。
結果が以下のものになります。
実行環境はWin8.1のマシンになります。

0.012998580932617188
0.010000228881835938
0.010999202728271484
0.011002779006958008
0.008002281188964844
0.009998798370361328
0.010000228881835938
0.00999903678894043
0.010000228881835938
0.010024309158325195
0.009996652603149414
0.010020017623901367
0.009978055953979492
0.010024309158325195
0.00997781753540039
0.010002374649047852
0.010028839111328125
0.010002613067626953

まあまあ正確?

環境構築(pyqt5を入れる)

python3系の何かとかpipとかは入っている前提で

Windowsの場合

pip install PyQt5

ubuntuとかraspbianとかの場合

 $sudo apt-get install python3-pyqt5

参考

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?