.. include:: /index.rst :start-after: start_hello_message :end-before: end_hello_message .. _py_tilt: 2.4 チルトスイッチ ===================== **はじめに** このプロジェクトでは、チルトスイッチモジュールを使用します。チルトスイッチは内部に小さな金属ボールを含むボール型スイッチで、わずかな傾きを検出することができます。このスイッチは、動作検知、角度検出、バランス監視など、さまざまな用途に利用できます。 ---------------------------------------------- **必要なもの** このプロジェクトを行うには、以下のコンポーネントを準備してください。 .. list-table:: :widths: 30 20 :header-rows: 1 * - COMPONENT INTRODUCTION - PURCHASE LINK * - :ref:`cpn_breadboard` - |link_breadboard_buy| * - :ref:`cpn_wires` - |link_wires_buy| * - :ref:`cpn_resistor` - |link_resistor_buy| * - :ref:`cpn_led` - |link_led_buy| * - :ref:`cpn_tilt_switch` - \- * - :ref:`cpn_fusion_hat` - \- * - Raspberry Pi - \- ---------------------------------------------- **回路図** チルトスイッチの接続方法については、以下の図を参照してください。 .. image:: img/fzz/2.1.5_sch.png :width: 100% :align: center ---------------------------------------------- **配線図** 以下の手順に従って回路を接続してください。 1. チルトスイッチをRaspberry PiのGPIO17に接続します。 2. 緑色LEDを抵抗を介してGPIO27に接続します。 3. 赤色LEDを抵抗を介してGPIO22に接続します。 4. 両方のLEDのカソードをGNDに接続します。 .. image:: img/fzz/2.1.5_bb.png :width: 80% :align: center ---------------------------------------------- **サンプルの実行** このチュートリアルで使用するすべてのサンプルコードは ``ai-lab-kit`` ディレクトリに含まれています。 以下の手順でサンプルを実行してください。 .. raw:: html .. code-block:: shell cd ~/ai-lab-kit/python/ sudo python3 2.4_Tilt.py このPythonスクリプトは、チルトセンサーを使用して2つのLEDを制御し、状態メッセージをコンソールに表示します。実行すると、次のように動作します。 1. チルトセンサー(GPIO17に接続)が傾きを検出した場合: - コンソールにメッセージを表示します。 - 赤色LED(GPIO22に接続)が点灯します。 - 緑色LED(GPIO27に接続)が消灯します。 2. チルトセンサーが直立状態(通常の垂直位置)の場合: - 赤色LEDが消灯します。 - 緑色LEDが点灯します。 3. プログラムはチルトセンサーの状態を継続的に監視し、それに応じてLEDを制御します。 4. ``Ctrl+C`` を押して中断するまで、スクリプトは継続して実行されます。 ---------------------------------------------- **コード** 以下は、チルトスイッチとLEDを制御するPythonスクリプトです。 .. raw:: html .. code-block:: python #!/usr/bin/env python3 from fusion_hat.pin import Pin, Mode, Pull from signal import pause # Import pause function from signal module TiltPin = Pin(17, mode=Mode.IN, pull=Pull.DOWN) # Tilt sensor connected to GPIO pin 17 green_led = Pin(27,mode=Mode.OUT) # Green LED connected to GPIO pin 27 red_led = Pin(22,mode=Mode.OUT) # Red LED connected to GPIO pin 22 def detect(): """ Detect the tilt sensor state and control the LEDs. Turns on the red LED and turns off the green LED when tilted. Turns off the red LED and turns on the green LED when not tilted. """ if TiltPin.value() == 0: # Check if the sensor is tilted print(' *************') print(' * Tilt! *') print(' *************') red_led.high() # Turn on red LED green_led.low() # Turn off green LED else: # If the sensor is not tilted red_led.low() # Turn off red LED green_led.high() # Turn on green LED try: # Set up a callback to detect changes in the tilt sensor state TiltPin.when_activated = detect TiltPin.when_deactivated = detect pause() except KeyboardInterrupt: # Handle KeyboardInterrupt (Ctrl+C) to exit the loop gracefully pass ---------------------------------------------- **コードの解説** 1. **インポート** スクリプトでは、LEDや入力ピンの制御に必要なクラスをインポートします。 .. code-block:: python from fusion_hat.pin import Pin, Mode, Pull from signal import pause # Import pause function from signal module 2. **初期化** チルトスイッチおよびLEDをGPIO17、GPIO27、GPIO22に接続して設定します。 .. code-block:: python TiltPin = Pin(17, mode=Mode.IN, pull=Pull.DOWN) # Tilt sensor connected to GPIO pin 17 green_led = Pin(27,mode=Mode.OUT) # Green LED connected to GPIO pin 27 red_led = Pin(22,mode=Mode.OUT) # Red LED connected to GPIO pin 22 3. **detect関数** ``detect`` 関数はチルトスイッチの状態を確認し、LEDの状態を更新します。スイッチが傾いた場合は赤色LEDが点灯し、緑色LEDは消灯します。 .. code-block:: python def detect(): if TiltPin.value() == 0: # Check if the sensor is tilted print(' *************') print(' * Tilt! *') print(' *************') red_led.high() # Turn on red LED green_led.low() # Turn off green LED else: # If the sensor is not tilted red_led.low() # Turn off red LED green_led.high() # Turn on green LED 4. **メインループ** チルトセンサーの ``when_pressed`` と ``when_released`` イベントに ``detect`` 関数を割り当てます。プログラムは中断されるまで実行され続けます。 .. code-block:: python try: # Set up a callback to detect changes in the tilt sensor state TiltPin.when_activated = detect TiltPin.when_deactivated = detect pause() except KeyboardInterrupt: # Handle KeyboardInterrupt (Ctrl+C) to exit the loop gracefully pass ---------------------------------------------- **トラブルシューティング** 1. **スクリプトが傾きに反応しない** - **原因**: ``when_activated`` および ``when_deactivated`` のイベントが正しく動作していない可能性があります。 - **対処方法**: ``detect()`` 関数が両方のイベントに正しく割り当てられていることを確認してください。 2. **LEDがちらつく** - **原因**: センサーのノイズやチャタリングの可能性があります。 - **対処方法**: 短い遅延を追加して信号を安定させます。 .. code-block:: python from time import sleep def detect(): sleep(0.05) # Debounce delay if TiltPin.value() == 0: red_led.on() green_led.off() else: red_led.off() green_led.on() ---------------------------------------------- **拡張アイデア** 1. **音によるフィードバック** チルトセンサーが作動したときにブザーで音による通知を追加できます。 .. code-block:: python from fusion_hat import Buzzer,Pin buzzer = Buzzer(Pin(4)) if TiltPin.value() == 0: buzzer.on() else: buzzer.off() 2. **時間ベースのアラート** センサーが一定時間以上傾いた状態のままの場合にアラートを発生させます。 .. code-block:: python from threading import Timer def alert(): print("Tilt detected for too long!") red_led.on() sleep(0.5) red_led.off() if TiltPin.value() == 0: Timer(5, alert).start() # Trigger alert if tilted for 5 seconds ---------------------------------------------- **まとめ** このプロジェクトでは、Fusion HAT+とチルトスイッチを使用して傾きを検出し、LEDを制御する方法を学びました。チルトスイッチは、簡単な動作検出や角度検出を実現する低コストなソリューションであり、ロボットやホームオートメーションなど多くの実用的な用途に活用できます。