.. note::

    Ciao, benvenuto nella SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community su Facebook! Approfondisci l'esplorazione del Raspberry Pi, Arduino ed ESP32 con altri appassionati.

    **Perché unirti a noi?**

    - **Supporto esperto**: Risolvi i problemi post-vendita e le sfide tecniche con l'aiuto della nostra comunità e del nostro team.
    - **Impara e condividi**: Scambia consigli e tutorial per migliorare le tue competenze.
    - **Anteprime esclusive**: Accedi in anteprima agli annunci di nuovi prodotti e alle anticipazioni esclusive.
    - **Sconti speciali**: Approfitta di sconti esclusivi sui nostri prodotti più recenti.
    - **Promozioni e omaggi festivi**: Partecipa a omaggi e promozioni speciali durante le festività.

    👉 Sei pronto a esplorare e creare con noi? Clicca su [|link_sf_facebook|] e unisciti oggi stesso!

.. _4.1.2_py:

4.1.2 Lettore musicale
==============================

Introduzione
-----------------

Nel progetto :ref:`3.1.3_py`, abbiamo fatto suonare una canzone agli altoparlanti. Ora aggiungiamo 3 pulsanti per controllare la riproduzione/pausa e il volume della musica.

Componenti necessari
------------------------------

In questo progetto avremo bisogno dei seguenti componenti.

.. image:: ../img/musicplayer_list.png
  :width: 800
  :align: center

È sicuramente conveniente acquistare un kit completo, ecco il link: 

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

    *   - Nome	
        - ELEMENTI IN QUESTO KIT
        - LINK
    *   - Kit Raphael
        - 337
        - |link_Raphael_kit|

Puoi anche acquistarli separatamente dai link sottostanti.

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

    *   - INTRODUZIONE AI COMPONENTI
        - LINK PER L'ACQUISTO

    *   - :ref:`cpn_gpio_extension_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_audio_speaker`
        - \-
    *   - :ref:`cpn_button`
        - |link_button_buy|

Schema elettrico
-----------------------

============ ======== ======== ===
T-Board Name physical wiringPi BCM
GPIO17       Pin 11   0        17
GPIO18       Pin 12   1        18
GPIO27       Pin 13   2        27
============ ======== ======== ===

.. image:: ../img/3.1.16_schematic.png
   :width: 600
   :align: center


Procedura sperimentale
------------------------------

**Passo 1:** Costruisci il circuito.

.. image:: ../img/3.1.16fritzing.png
  :width: 800
  :align: center

Dopo aver costruito il circuito secondo lo schema sopra, collega il cavo audio al jack audio da 3,5 mm del Raspberry Pi.

.. image:: ../img/audio4.png
    :width: 400
    :align: center


**Passo 2:** Accedi alla cartella del codice.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python/

**Passo 3:** Esegui.

.. raw:: html

   <run></run>

.. code-block::

    python3 4.1.2_MusicPlayer.py

Dopo l'esecuzione del codice, il Raspberry Pi riprodurrà il file ``my_music.mp3`` nella directory ``~/raphael-kit/music``.

* Il pulsante 1 mette in pausa/riprende la musica.
* Il pulsante 2 riduce il volume.
* Il pulsante 3 aumenta il volume.

Se desideri caricare altri file musicali sul Raspberry Pi, fai riferimento a :ref:`filezilla`.

**Codice**

.. note::
    Puoi **Modificare/Resettare/Copiare/Eseguire/Fermare** il codice qui sotto. Ma prima di farlo, devi andare nel percorso del codice sorgente, come ``raphael-kit/python``. Dopo aver modificato il codice, puoi eseguirlo direttamente per vedere l'effetto.

.. raw:: html

    <run></run>

.. code-block:: python

    from pygame import mixer
    import RPi.GPIO as GPIO
    import time
    import os
    user = os.getlogin()
    user_home = os.path.expanduser(f'~{user}')

    BtnPin1 = 18
    BtnPin2 = 17
    BtnPin3 = 27
    volume = 0.7

    status = False
    upPressed = False
    downPressed = False
    playPressed = False

    def setup():
        mixer.init()
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(BtnPin1, GPIO.IN, GPIO.PUD_UP)
        GPIO.setup(BtnPin2, GPIO.IN, GPIO.PUD_UP)
        GPIO.setup(BtnPin3, GPIO.IN, GPIO.PUD_UP)

    def clip(x,min,max):
        if x < min:
            return min
        elif x > max:
            return max
        return x

    def play(pin):
        global playPressed
        playPressed = True

    def volDown(pin):
        global downPressed
        downPressed = True

    def volUp(pin):
        global upPressed
        upPressed = True

    def main():
        global volume, status
        global downPressed, upPressed, playPressed
        mixer.music.load(f'{user_home}/raphael-kit/music/my_music.mp3')
        mixer.music.set_volume(volume)
        mixer.music.play()
        GPIO.add_event_detect(BtnPin1, GPIO.FALLING, callback=play)
        GPIO.add_event_detect(BtnPin2, GPIO.FALLING, callback=volDown)
        GPIO.add_event_detect(BtnPin3, GPIO.FALLING, callback=volUp)
        while True:
            if upPressed:
                volume = volume + 0.1
                upPressed = False
            if downPressed:
                volume = volume - 0.1
                downPressed = False
            if playPressed:
                if status:
                    mixer.music.pause()
                    status = not status
                else:
                    mixer.music.unpause()
                    status = not status
                playPressed = False
                time.sleep(0.5)
            volume = clip(volume,0.2,1)
            mixer.music.set_volume(volume)
            time.sleep(0.1)

    def destroy():
        # Rilascia risorse
        GPIO.cleanup()
        mixer.music.stop()

    # Se esegui questo script direttamente, fai:
    if __name__ == '__main__':
        setup()
        try:
            main()
        # Quando viene premuto 'Ctrl+C', il programma 
        # destroy() sarà eseguito.
        except KeyboardInterrupt:
            destroy()

**Spiegazione del Codice**

.. code-block:: python

    from pygame import mixer

    mixer.init()

Importa il metodo ``Mixer`` dalla libreria ``pygame`` e inizializza il metodo.

.. code-block:: python

    BtnPin1 = 18
    BtnPin2 = 17
    BtnPin3 = 27
    volume = 0.7

Definisci le porte dei pin dei tre pulsanti e imposta il volume iniziale a 0.7.

.. code-block:: python

    upPressed = False
    downPressed = False
    playPressed = False

``upPressed``, ``downPressed`` e ``playPressed`` sono tutte bandiere di interruzione; quando diventano ``True``, viene eseguita l'azione corrispondente.

.. code-block:: python

    def clip(x,min,max):
    if x < min:
        return min
    elif x > max:
        return max
    return x

La funzione ``clip()`` serve a impostare i limiti superiori e inferiori dei parametri di input.

.. code-block:: python

    GPIO.add_event_detect(BtnPin1, GPIO.FALLING, callback=play)
    GPIO.add_event_detect(BtnPin2, GPIO.FALLING, callback=volDown)
    GPIO.add_event_detect(BtnPin3, GPIO.FALLING, callback=volUp)

Imposta gli eventi di rilevamento per i pulsanti ``BtnPin1``, ``BtnPin2`` e ``BtnPin3``.

* Quando viene premuto ``BtnPin1``, viene eseguita la funzione di interruzione ``play()``.
* Quando viene premuto ``BtnPin2``, viene eseguita la funzione di interruzione ``volDown()``.
* Quando viene premuto ``BtnPin3``, viene eseguita la funzione di interruzione ``volUp()``.

Immagine del fenomeno
--------------------------

.. image:: ../img/4.1.2musicplayer.JPG
   :align: center

