Note
こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ!Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。
参加する理由は?
- エキスパートサポート:コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。
- 学び&共有:ヒントやチュートリアルを交換してスキルを向上させましょう。
- 独占的なプレビュー:新製品の発表や先行プレビューに早期アクセスしましょう。
- 特別割引:最新製品の独占割引をお楽しみください。
- 祭りのプロモーションとギフト:ギフトや祝日のプロモーションに参加しましょう。
👉 私たちと一緒に探索し、創造する準備はできていますか?[]をクリックして今すぐ参加しましょう!
このプロジェクトでは、ボタンを使用してLEDをオンまたはオフにする方法を学びます。
このプロジェクトには、次のコンポーネントが必要です。
一式を購入するのが便利です、こちらがリンクです:
名前 | このキットのアイテム | リンク |
---|---|---|
Raphael Kit | 337 |
以下のリンクから別々に購入することもできます。
コンポーネントの紹介 | 購入リンク |
---|---|
cpn_gpio_board |
|
cpn_breadboard |
|
cpn_wires |
|
cpn_resistor |
|
cpn_led |
|
cpn_button |
Raspberry Piの入力として通常開放ボタンを使用し、接続は以下の回路図に示す通りです。ボタンが押されると、GPIO18は高レベル(3.3V)になります。プログラムを介してGPIO18の状態を検出できます。つまり、GPIO18が高レベルになると、ボタンが押されたことを意味します。ボタンが押されたときに対応するコードを実行し、LEDが点灯します。
Note
LEDの長いピンが陽極であり、短いピンが陰極です。
ステップ1: 回路を組み立てます。
ステップ2: コードファイルを開きます。
cd ~/raphael-kit/python-pi5
ステップ3: コードを実行します。
sudo python3 2.1.1_Button_zero.py
ボタンを押すとLEDが点灯し、ボタンを離すとLEDが消灯します。
コード
Note
以下のコードを 変更/リセット/コピー/実行/停止 できます。ただし、それに先立ち、 raphael-kit/python_5
のようなソースコードのパスに移動する必要があります。コードを変更した後、効果を直接確認するために実行できます。
#!/usr/bin/env python3
from gpiozero import LED, Button # Import LED and Button classes from gpiozero
from signal import pause # Import pause function from signal module
# Initialize an LED object on GPIO pin 17
led = LED(17)
# Initialize a Button object on GPIO pin 18
button = Button(18)
# Link the button's "when_pressed" event to the LED's on() method
button.when_pressed = led.on
# Link the button's "when_released" event to the LED's off() method
button.when_released = led.off
# Run an event loop that waits for button events and keeps the script running
pause()
コードの説明
このスクリプトはPython3で書かれており、
gpiozero
ライブラリからLED
およびButton
クラス、signal
モジュールからpause
をインポートしています。#!/usr/bin/env python3 from gpiozero import LED, Button # Import LED and Button classes from gpiozero from signal import pause # Import pause function from signal module
GPIOピン17に接続されたLEDオブジェクトとGPIOピン18に接続されたボタンオブジェクトを初期化します。
# Initialize an LED object on GPIO pin 17 led = LED(17) # Initialize a Button object on GPIO pin 18 button = Button(18)
ボタンが押されたときにLEDが点灯し、ボタンが離されたときにLEDが消灯するようにイベントハンドラを設定します。
# Link the button's "when_pressed" event to the LED's on() method button.when_pressed = led.on # Link the button's "when_released" event to the LED's off() method button.when_released = led.off
ボタンの押下およびリリースイベントを待ち続けるために、スクリプトをイベントループ内で実行し続けます。
# Run an event loop that waits for button events and keeps the script running pause()