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?

ラズパイによるスターターキットの部品導通記録②~Switch + LED

Last updated at Posted at 2026-01-22

前述の記事、ラズパイによるスターターキットの部品導通記録①~LED
の回路を生かし、スイッチを押したときに、LEDが点灯するような処理を追加した

環境

HW/SW バージョン他
筐体 Rasberry zero
OS RasberryPi OS (32-bit)
python 3.13.5
部品① LED
部品② Tactile Switch Buttons (12mm square, 6mm tall)
その他部品 ブレッドボード、ジャンパーワイアー、抵抗(1kΩ)

テキスト回路図

■部品① LED
Rasberry ZERO(GPIO17:物理ピン11) → 抵抗(1kΩ) → (+)LED(-) → ※
※ → Rasberry ZERO(GND:物理ピン9)

■部品② スイッチ
Rasberry ZERO(GPIO23:物理ピン16) → スイッチ → Rasberry ZERO(3.3V:物理ピン1)

プログラム仕様
・スイッチを押下している間は、LEDが点灯し、スイッチを離すとLEDは消灯
・スイッチの状態[ON]、[OFF]をコンソール出力
・やめるときは、[Ctl] + [c]

プログラムソース

switch_led.py
#!/usr/bin/python
#必要なモジュールをインポート
import RPi.GPIO as GPIO             #GPIO用のモジュールをインポート
import time                         #時間制御用のモジュールをインポート
import sys                          #sysモジュールをインポート

#ポート番号の定義
Sw_pin = 23                         #変数"Sw_pin"に23を格納 物理ピン16のこと
Led_pin = 17                        #変数"Led_pin"に17を格納 物理ピン11のこと

#GPIOの設定
GPIO.setmode(GPIO.BCM)              #GPIOのモードを"GPIO.BCM"に設定
GPIO.setwarnings(False)

# 使用する GPIO をすべて出力に設定
GPIO.setup(Led_pin, GPIO.OUT)

#GPIO23を入力モードに設定してプルダウン抵抗を有効にする
GPIO.setup(Sw_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

#while文で無限ループ
#GPIO23の入力を読み取る
while True:
    try:
        judge = GPIO.input(Sw_pin)
        time.sleep(0.02) #デバウンス(20ms) スイッチのバタつき防止
        if judge:
            print("ON") #GPIO23が「ONで"1"」「OFFで"0"」
            GPIO.output(Led_pin, GPIO.HIGH)    # LED ON
        else:
            print("OFF") #GPIO23が「ONで"1"」「OFFで"0"」
            GPIO.output(Led_pin, GPIO.LOW)     # LED OFF

        time.sleep(1)                         #1秒間待つ

    except KeyboardInterrupt:               #Ctrl+Cキーが押された
        GPIO.cleanup()                      #GPIOをクリーンアップ
        sys.exit()                          #プログラムを終了

実行

pi@pi32lite:~/gpio $ python switch_led.py
OFF
OFF
OFF
ON
ON
OFF
OFF
^C
pi@pi32lite:~/gpio $
消灯時 スイッチ押下時
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?