GPIO 操作するプログラムを macOS で開発する
概要
macOS 環境で RPi.GPIO モジュールを使用します。 macOS 環境では GPIO が存在しないため、エミュレーターを使用します。 なお、エミュレーターは自作です。
確認環境
- Raspberry Pi Zero
- RASPBIAN JESSIE LITE 2016-11-25
- Python 3.4.2
- MacBook Pro 2016 Late
参考情報
- Raspberry Pi GPIO Emulator | Roderick Vella Galea
- Raspberry Pi GPIO Emulator
- GitHub - nosix/raspberry-gpio-emulator: RPi.GPIO emulator
- 自作の RPi.GPIO Emulator
前回の記事
解説
Raspberry Pi には RPi.GPIO モジュールがインストールされているが、macOS 環境にはインストールされていない。 例えば、以下のプログラムを macOS 環境の PyCharm で作成すると No module named RPi とのエラーメッセージが表示される。
hello_gpio.py
from time import sleep import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) while True: GPIO.output(25, GPIO.HIGH) sleep(0.5) GPIO.output(25, GPIO.LOW) sleep(0.5)
macOS 環境に RPi モジュールをインストールする代わりに RPi モジュールのエミュレーター(もしくは、シミュレーター)を探した。 いくつか見つかったが、モジュール名を変更しなければいけないなど、ソースコード(上記の例では hello_gpio.py)に全く手を入れずに使えるものではなかった。そこで、RPi モジュールのエミュレーターを自作した。
RPi.GPIO エミュレーターをインストールする
GitHub にある Python パッケージを pip を使って仮想環境にインストール。
mac:~ nosix$ source ~/pyenv/python3/bin/activate (python3) mac:~ nosix$ (python3) mac:~ nosix$ pip install git+https://github.com/nosix/raspberry-gpio-emulator/ Collecting git+https://github.com/nosix/raspberry-gpio-emulator/ Cloning https://github.com/nosix/raspberry-gpio-emulator/ to /private/var/folders/kz/wv_kdss90634rlck2k9d852m0000gn/T/pip-6akufwi3-build Installing collected packages: RPi Running setup.py install for RPi ... done Successfully installed RPi-0.1.0
インストールが完了するとエラーは消える。
macOS 環境、Raspberry Pi 環境のいずれでも変更なしで実行できる。
macOS 環境で実行した場合には、エミュレーターが起動されてピンの状態を表示。
Raspberry Pi 環境で実行した場合には、GPIO が操作される。
なお、エミュレーターの UI が気に入らない場合には、自作 UI に差し替えられる設計になっている。 また、各 GPIO の状態変化を監視するプラグインを追加できる様になっている。