インストール - RPi.GPIO
ナビゲーションに移動
検索に移動
概要
ここでは、Python3用のRPi.GPIOモジュールのインストール方法を記載する。
RPi.GPIOモジュールのインストール
まず、Raspberry Pi OSのアップデートを行う。
sudo apt update sudo apt upgrade
次に、pipのインストールを行う。
sudo apt install python3-pip
Python3のRPi.GPIOモジュールをインストールする。
sudo apt install python3-rpi.gpio # または sudo pip3 install RPi.GPIO
確認
Python 3を使用して、モジュールをインポートできることを確認する。
このとき、import RPi.GPIOコマンドは出力を返さなければ成功である。(モジュールが正常にインポートされたことを意味する)
python3
import RPi.GPIO
RPi.GPIOを使用したサンプルコード
# Import necessary modules
import RPi.GPIO as GPIO
import time
# Set up GPIO pins
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pins = [17,18]
for pin in pins:
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin,1)
# Set variables (change these to change behaviour as desired)
runcycles = 2
ontime = 45 # minutes
offtime = 20 # minutes
# Convert run times from minutes to seconds for sleep function
ontime *= 60
offtime *= 60
# Run furnace on cycle
cycle = 0
try:
while cycle < runcycles:
cycle += 1
GPIO.output(17,0)
print("Furnace turned on for %d seconds. Cycle %d of %d." %(ontime, cycle, runcycles))
time.sleep(ontime)
GPIO.output(17,1)
if cycle == runcycles:
break
print("Furnace paused for %s seconds. %s heat cycles remaining." %(offtime, runcycles - cycle))
time.sleep(offtime)
except KeyboardInterrupt: # if Ctrl C is pressed...
GPIO.output(17,1) # shut off the boiler
print("Program stopped and furnace shut off.") # print a clean exit message
print("Heat cycles completed.")