.. note::

    こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ！Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。

    **参加する理由は？**

    - **エキスパートサポート**：コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。
    - **学び＆共有**：ヒントやチュートリアルを交換してスキルを向上させましょう。
    - **独占的なプレビュー**：新製品の発表や先行プレビューに早期アクセスしましょう。
    - **特別割引**：最新製品の独占割引をお楽しみください。
    - **祭りのプロモーションとギフト**：ギフトや祝日のプロモーションに参加しましょう。

    👉 私たちと一緒に探索し、創造する準備はできていますか？[|link_sf_facebook|]をクリックして今すぐ参加しましょう！

.. _1.2.2_py_pi5:


1.2.2 パッシブブザー
=====================

はじめに
------------

このプロジェクトでは、パッシブブザーを使用して音楽を演奏する方法を学びます。

必要な部品
------------------------------

このプロジェクトには、次のコンポーネントが必要です。 

.. image:: ../python_pi5/img/1.2.2_passive_buzzer_list.png

一式を購入するのが便利です、こちらがリンクです： 

.. list-table::
    :widths: 20 20 20
    :header-rows: 1

    *   - 名前	
        - このキットのアイテム
        - リンク
    *   - Raphael Kit
        - 337
        - |link_Raphael_kit|

以下のリンクから別々に購入することもできます。

.. list-table::
    :widths: 30 20
    :header-rows: 1

    *   - コンポーネントの紹介
        - 購入リンク

    *   - :ref:`cpn_gpio_board`
        - |link_gpio_board_buy|
    *   - :ref:`cpn_breadboard`
        - |link_breadboard_buy|
    *   - :ref:`cpn_wires`
        - |link_wires_buy|
    *   - :ref:`cpn_resistor`
        - |link_resistor_buy|
    *   - :ref:`cpn_buzzer`
        - |link_passive_buzzer_buy|
    *   - :ref:`cpn_transistor`
        - |link_transistor_buy|

回路図
-----------------

この実験では、パッシブブザー、PNPトランジスタ、および1kΩの抵抗器が、トランジスタのベースとGPIOの間に使用されてトランジスタを保護します。

GPIO17に異なる周波数が供給されると、パッシブブザーは異なる音を鳴らします。これにより、ブザーは音楽を演奏します。

============ ======== ===
T-Board Name physical BCM
GPIO17       Pin 11   17
============ ======== ===

.. image:: ../python_pi5/img/1.2.2_passive_buzzer_schematic.png


実験手順
-----------------------

**ステップ1**: 回路を組み立てます（パッシブブザーは裏面に緑の回路基板があります）。

.. image:: ../python_pi5/img/1.2.2_PassiveBuzzer_circuit.png

**ステップ2: ディレクトリを変更します。**

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python-pi5

**ステップ3: 実行します。**

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 1.2.2_PassiveBuzzer_zero.py

コードを実行すると、ブザーが音楽を演奏します。

.. warning::

    エラー メッセージ ``RuntimeError: Cannot determine SOC peripheral base address`` が表示された場合は、 :ref:`faq_soc` を参照してください。

**コード**

.. note::

    以下のコードは変更/リセット/コピー/実行/停止ができます。ただし、コードを変更する前に ``raphael-kit/python_5`` のようなソースコードのパスに移動する必要があります。コードを変更した後、直接実行して効果を確認できます。


.. raw:: html

    <run></run>

.. code-block:: python

   #!/usr/bin/env python3
   from gpiozero import TonalBuzzer
   from time import sleep

   # Initialize a TonalBuzzer connected to GPIO pin 17
   tb = TonalBuzzer(17)  # Update this pin number based on your setup

   def play(tune):
       """
       Play a musical tune using the buzzer.
       :param tune: List of tuples (note, duration), where each tuple represents a note and its duration.
       """
       for note, duration in tune:
           print(note)  # Output the current note being played
           tb.play(note)  # Play the note on the buzzer
           sleep(float(duration))  # Delay for the duration of the note
       tb.stop()  # Stop playing after the tune is complete

   # Define a musical tune as a sequence of notes and durations
   tune = [('C#4', 0.2), ('D4', 0.2), (None, 0.2),
       ('Eb4', 0.2), ('E4', 0.2), (None, 0.6),
       ('F#4', 0.2), ('G4', 0.2), (None, 0.6),
       ('Eb4', 0.2), ('E4', 0.2), (None, 0.2),
       ('F#4', 0.2), ('G4', 0.2), (None, 0.2),
       ('C4', 0.2), ('B4', 0.2), (None, 0.2),
       ('F#4', 0.2), ('G4', 0.2), (None, 0.2),
       ('B4', 0.2), ('Bb4', 0.5), (None, 0.6),
       ('A4', 0.2), ('G4', 0.2), ('E4', 0.2), 
       ('D4', 0.2), ('E4', 0.2)]

   try:
       play(tune)  # Execute the play function to start playing the tune

   except KeyboardInterrupt:
       # Handle KeyboardInterrupt for graceful termination
       pass



**コードの説明**

1. これらの行はブザーの制御のために ``gpiozero`` ライブラリから ``TonalBuzzer`` クラス、待機を作成するために ``time`` モジュールから ``sleep`` 関数をインポートします。

   .. code-block:: python
       
       #!/usr/bin/env python3
       from gpiozero import TonalBuzzer
       from time import sleep


2. この行はGPIOピン17に接続された ``TonalBuzzer`` オブジェクトを初期化します。
    
   .. code-block:: python
       
       # Initialize a TonalBuzzer connected to GPIO pin 17
       tb = TonalBuzzer(17)  # Update this pin number based on your setup
        

3. ``play`` 関数は、音楽のノートとその持続時間を表すタプルのリストを繰り返し処理します。各ノートは指定された持続時間だけ演奏され、曲が終了するとブザーが停止します。
    
   .. code-block:: python  

       def play(tune):
           """
           Play a musical tune using the buzzer.
           :param tune: List of tuples (note, duration), where each tuple represents a note and its duration.
           """
           for note, duration in tune:
               print(note)  # Output the current note being played
               tb.play(note)  # Play the note on the buzzer
               sleep(float(duration))  # Delay for the duration of the note
           tb.stop()  # Stop playing after the tune is complete

4. メロディは音符（周波数）と持続時間（秒）のシーケンスとして定義されています。
    
   .. code-block:: python

       # Define a musical tune as a sequence of notes and durations
       tune = [('C#4', 0.2), ('D4', 0.2), (None, 0.2),
           ('Eb4', 0.2), ('E4', 0.2), (None, 0.6),
           ('F#4', 0.2), ('G4', 0.2), (None, 0.6),
           ('Eb4', 0.2), ('E4', 0.2), (None, 0.2),
           ('F#4', 0.2), ('G4', 0.2), (None, 0.2),
           ('C4', 0.2), ('B4', 0.2), (None, 0.2),
           ('F#4', 0.2), ('G4', 0.2), (None, 0.2),
           ('B4', 0.2), ('Bb4', 0.5), (None, 0.6),
           ('A4', 0.2), ('G4', 0.2), ('E4', 0.2), 
           ('D4', 0.2), ('E4', 0.2)]  

5. ``play(tune)`` 関数は ``try`` ブロック内で呼び出されます。 ``KeyboardInterrupt`` （Ctrl+Cのような）はプログラムを正常に停止します。
    
   .. code-block:: python  
       
       try:
           play(tune)  # Execute the play function to start playing the tune

       except KeyboardInterrupt:
           # Handle KeyboardInterrupt for graceful termination
           pass
