ラズパイエラー GPIOでPWM制御を繰り返し行うとカメラが反応しなくなる

picamera.exc.PiCameraRuntimeError

RaspberryPiでエラー。カメラが停止するというもの。どうやらPWMを使っていると発生する模様。モーターの動作/停止を頻繁に行っている時に発生します。

表示されるエラー

picamera.exc.PiCameraRuntimeError: Timed out waiting for capture to end

・・・picameraが応答しなくなります。

エラーが出た環境など

ざっくりですが・・・メモ程度に。

  • Raspberry Pi 3 Model B
  • Raspberry Pi カメラモジュール V2
  • サーボモーター SG90(PWM制御)
  • import picamera
  • import RPi.GPIO

サーボモーターのstart()、stop()を繰り返していると、スレッドがいっぱいになってしまうため停止する模様。確かに、毎回同じ回数(数百回)で止まるのでそれっぽい。

【参考】
https://sourceforge.net/p/raspberry-gpio-python/tickets/94/

I have looked a bit into this issue and main problem seems to be related to Linux threads. Library creates/destroys posix thread at every start/stop pwm. On my RPi I am able to create and destroy only 380 threads within single process. After that threshold pthread_create always returns error code 11. See test code in attachment.
I suggest solution to create thread per GPIO just once and then sleep it with mutex or something to prevent too many create/destroy cycles.

回避策

start()、stop()の代わりにChangeDutyCycle()を使えば大丈夫というコメントもあったのですが、うまくいかなかったです。

遊びの延長ということもあり、手っ取り早く回避するために、PWM制御のライブラリをWiringPi2 for Pythonに変更したらエラーは出なくなりました。

今のところ1000回以上繰り返しても問題ないです。