1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ラズパイ5でハードウェアPWMをPythonから動かしてみた

Last updated at Posted at 2025-08-24

最初に結論

  • RaspberryPi 5でrpi_hardware_pwmなるモジュールを実行してみた
  • 実行はできて、サーボモータのジッターが見えなくなったことを確認
  • /sys/kernel/debug/pwmにもちゃんと設定が反映されていたことを確認

rpi_hardware_pwmについて

以下参照。
軽量なハードウェアPWMが使えるモジュール。
ラズパイ5以外にも4などでも使用可能。

環境

  • RaspberryPi 5 8GB
  • RaspberryPi OS 12(Bookworm) x64
    • CLIしか使わなかったけどwith desktopの方
  • rpi-hardware-pwmは0.3.0が入った
  • サーボモーターはGeekServo Gray

実施したこと

事前にsudo nano /boot/hardware/config.txtなどで下記の文言を[all]の欄に追加
今回はpin12とpin13を使う設定にした。

dtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4

image.png

externally-managed-environmentのエラーが出たので、以下の強制力強めのコマンドを実行。嫌であれば仮想環境上のPythonで実行するのが良いのかな。

sudo pip install --break-system-packages rpi-hardware-pwm

以下のコードを作成し、実行
Ctrl+Xで止めるまで一定の角度への移動を5秒おきに繰り返す処理を実行しており、待機時間にジッターが起きないか確認

ちなみにPWMピンはGPIO12へ接続

pwm_test.py
rom rpi_hardware_pwm import HardwarePWM
import time

pwm = HardwarePWM(pwm_channel=0, hz=50, chip=0)
pwm.start(0)

try:
    while True:
        # 0度
        pwm.change_duty_cycle(2.5)
        time.sleep(5)
        # 90度
        pwm.change_duty_cycle(7.5)
        time.sleep(5)
        # 180度
        pwm.change_duty_cycle(12.5)
        time.sleep(5)
except KeyboardInterrupt:
    print("プログラムを終了します")
finally:

実行コマンドは下記

python pwm_test.py

実行結果

ジッターなどはなく、きれいに移動している。

以下コマンドにてハードウェアPWMとして設定が反映されていることも確認。ちなみにlsmod | grep pwmだと何も出てこなかった。謎だ~

sudo cat /sys/kernel/debug/pwm

image.png

まとめ

  • ハードウェアPWMがやっとラズパイ5で使えた!
    • ジッターが無いのはやっぱり嬉しい!
  • lsmodでpwm-...が出てこなかったのでむっちゃ焦った
  • externally-managed-environmentが出ないクリーンな環境も作ってみたいところ

参考文献

実を言うとこちらの記事の内容をRaspberryPi5で試してみただけだったり。感謝です。

特に最後のilw氏のOther useful commandsに救われた。ありがとうございます。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?