.. include:: /index.rst :start-after: start_hello_message :end-before: end_hello_message .. _py_relay: 1.5 リレー制御 =========================== **はじめに** このプロジェクトでは、Raspberry Pi を使ってリレーモジュールを制御する方法を学びます。リレーは電気的に動作するスイッチであり、低電力回路から高電力デバイスを安全に制御できます。このプロジェクトでは、一定間隔でリレーをオン・オフする基本動作を確認します。 ---------------------------------------------- **必要なもの** このプロジェクトを完成させるには、以下の部品が必要です。 .. list-table:: :widths: 30 20 :header-rows: 1 * - 部品 - 購入リンク * - :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_transistor` - |link_transistor_buy| * - :ref:`cpn_relay` - |link_relay_buy| * - :ref:`cpn_diode` - |link_diode_buy| * - :ref:`cpn_fusion_hat` - \- * - Raspberry Pi - \- ---------------------------------------------- **回路図** GPIO 信号は 1 kΩ 抵抗を介してトランジスタのベースに入力され、これによりトランジスタがリレーコイルのオン・オフを切り替えます。GPIO17 が HIGH を出力するとトランジスタが導通し、リレーコイルに電流が流れてリレーが動作し、LED も 220 Ω 抵抗を介して点灯します。GPIO17 が LOW を出力するとトランジスタはオフになり、リレーコイルへの通電が止まり、リレーは復帰し、LED も消灯します。さらに、リレーコイルには逆起電力による電圧スパイクから回路を保護するため、フライバックダイオードが接続されています。 .. image:: img/fzz/1.3.3_relay_sch.png ---------------------------------------------- **配線図** 以下の図を参考にして回路を組み立ててください。 .. image:: img/fzz/1.3.3_relay_bb.png :width: 90% :align: center ---------------------------------------------- **サンプルプログラムの実行** このチュートリアルで使用するすべてのサンプルコードは ``ai-lab-kit`` ディレクトリに用意されています。 以下の手順でサンプルを実行してください。 .. raw:: html .. code-block:: shell cd ~/ai-lab-kit/python/ sudo python3 1.5_Relay.py スクリプトを実行すると、GPIO 17 に接続されたリレーが 1 秒ごとにオン・オフを繰り返します。リレーがオンになるとコンソールには ``Relay open...`` と表示され、オフになると ``...Relay close`` と表示されます。この動作は ``Ctrl + C`` を押すまで繰り返され、停止時にはプログラムが終了し、リレーは安全にオフになります。 ---------------------------------------------- **コード** 以下の Python コードは、リレーモジュールを制御してオン・オフを繰り返します。 .. raw:: html .. code-block:: python #!/usr/bin/env python3 from fusion_hat.pin import Pin, Mode from time import sleep # Import the sleep function for delay # Initialize the relay connected to GPIO pin 17 relay = Pin(17,mode=Mode.OUT) try: # Loop to continuously toggle the relay's state every second while True: print('Relay open...') # Inform that the relay is being activated relay.high() # Turn on the relay sleep(1) # Maintain the relay in the on state for 1 second print('...Relay close') # Inform that the relay is being deactivated relay.low() # Turn off the relay sleep(1) # Maintain the relay in the off state for 1 second except KeyboardInterrupt: # Handle a keyboard interrupt (Ctrl+C) to exit the loop relay.off() # Ensure the relay is turned off before exiting pass この Python スクリプトは GPIO ピン 17 に接続されたリレーモジュールを制御します。実行すると、次のように動作します。 1. スクリプトは無限ループに入り、1 秒ごとにリレーの状態を切り替えます。 2. リレーが有効化される(HIGH)と、コンソールに ``Relay open...`` と表示されます。 3. リレーが無効化される(LOW)と、コンソールに ``...Relay close`` と表示されます。 4. ``Ctrl+C`` によって安全に中断でき、その際は終了前に必ずリレーがオフになります。 ---------------------------------------------- **コードの理解** 1. **ライブラリのインポート** ``fusion_hat`` ライブラリの ``Pin`` クラスを使って GPIO ピンを制御し、 ``time.sleep`` を使って状態の切り替え間に待ち時間を入れています。 .. code-block:: python from fusion_hat.pin import Pin, Mode from time import sleep # Import the sleep function for delay 2. **リレーの初期化** リレーは GPIO ピン 17 に接続され、出力モードとして初期化されます。 .. code-block:: python # Initialize the relay connected to GPIO pin 17 relay = Pin(17,mode=Mode.OUT) 3. **メイン制御ループ** ``while True`` ループの中で、1 秒間隔でリレーの状態を切り替え続けます。 .. code-block:: python while True: print('Relay open...') # Inform that the relay is being activated relay.high() # Turn on the relay sleep(1) # Maintain the relay in the on state for 1 second print('...Relay close') # Inform that the relay is being deactivated relay.low() # Turn off the relay sleep(1) # Maintain the relay in the off state for 1 second 4. **キーボード割り込み処理** ``try-except`` ブロックにより、 ``Ctrl+C`` などでプログラムを中断しても安全に終了でき、終了前にリレーをオフにします。 .. code-block:: python except KeyboardInterrupt: # Handle a keyboard interrupt (Ctrl+C) to exit the loop relay.off() # Ensure the relay is turned off before exiting pass ---------------------------------------------- **トラブルシューティング** 1. **リレーが反応しない** - **原因**:配線ミス、または GPIO ピンの設定が誤っている。 - **対処方法**:すべての接続が配線図どおりになっているか確認し、GPIO 17 が正しく指定されていることを確認してください。 2. **リレーが常にオン、またはオフのままになる** - **原因**:ロジックレベルの不一致、または電源供給の問題。 - **対処方法**:リレーモジュールが 3.3V ロジックに対応していることを確認し、十分な電源が供給されているか確認してください。 3. **プログラムが正常に終了しない** - **原因**:キーボード割り込みが正しく処理されていない。 - **対処方法**: ``Ctrl+C`` でプログラムを終了し、例外処理コードが正しく含まれていることを確認してください。 ---------------------------------------------- **発展アイデア** 1. **スケジュール制御** コードを変更して、特定の時刻にリレーをオン・オフするようにできます。 .. code-block:: python import datetime # Turn relay on during specific hours current_time = datetime.datetime.now().time() if datetime.time(9, 0) <= current_time <= datetime.time(17, 0): relay.high() else: relay.low() 2. **センサー連動制御** 温度センサーや人感センサーなどを接続し、その読み取り値に応じてリレーを制御できます。 .. code-block:: python # Pseudocode for sensor-controlled relay if temperature_sensor.read() > 25: # If temperature exceeds 25°C relay.high() # Turn on cooling device else: relay.low() # Turn off cooling device 3. **複数リレーの制御** このプロジェクトを拡張して、複数のリレーを同時に制御することもできます。 .. code-block:: python # Initialize multiple relays relays = { 'light': Pin(17, Pin.OUT), 'fan': Pin(18, Pin.OUT), 'pump': Pin(19, Pin.OUT) } # Control individual relays relays['light'].high() relays['fan'].low() ---------------------------------------------- **まとめ** このプロジェクトでは、Raspberry Pi を使ってリレーモジュールを制御する方法を学びました。リレーはホームオートメーション、産業用制御システム、IoT アプリケーションにおける基本的な部品です。リレー制御を習得することで、低電圧回路から高電力デバイスを安全かつ効果的に操作できるようになります。