.. 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.1_py:

4.1.1 Fotocamera
============================

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

Qui realizzeremo una fotocamera con un otturatore: quando premi il pulsante, la fotocamera scatta mentre il LED lampeggia.

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

In questo progetto avremo bisogno dei seguenti componenti.

.. image:: ../img/3.1.15camera_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_led`
        - |link_led_buy|
    *   - :ref:`cpn_button`
        - |link_button_buy|
    *   - :ref:`cpn_camera_module`
        - |link_camera_buy|

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

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

.. image:: ../img/camera_schematic.png
   :width: 500
   :align: center

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

**Passo 1:** Costruisci il circuito.

.. image:: ../img/3.1.15camera_fritzing.png
  :width: 800
  :align: center

**Passo 2:** Per collegare il modulo fotocamera e completare la configurazione, fai riferimento a: :ref:`cpn_camera_module`.

**Passo 3:** Accedi al desktop del Raspberry Pi. Potresti aver bisogno di uno schermo per un'esperienza migliore, fai riferimento a: `Collega il tuo Raspberry Pi <https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up/3>`_. Oppure accedi al desktop del Raspberry Pi da remoto, per un tutorial dettagliato fai riferimento a :ref:`remote_desktop`.

**Passo 4:** Apri un terminale e accedi alla cartella del codice.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python/

**Passo 5:** Esegui.

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 4.1.1_Camera.py

Dopo l'esecuzione del codice, premi il pulsante: il Raspberry Pi farà lampeggiare il LED e scatterà una foto. La foto sarà nominata ``my_photo.jpg`` e salvata nella directory ``~``.

.. note::

    Puoi anche aprire ``4.1.1_Camera.py`` nel percorso ``~/raphael-kit/python/`` con un IDE Python, clicca sul pulsante Run per eseguire e sul pulsante Stop per interrompere il codice.

Se desideri scaricare la foto sul tuo PC, 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

	#!/usr/bin/env python3

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


	camera = PiCamera()

	LedPin = 17 # Imposta GPIO17 come pin LED
	BtnPin = 18 # Imposta GPIO18 come pin del pulsante

	status = False

	def setup():
		GPIO.setmode(GPIO.BCM)
		GPIO.setup(LedPin, GPIO.OUT, initial=GPIO.HIGH)
		GPIO.setup(BtnPin, GPIO.IN)
		camera.start_preview(alpha=200)

	def takePhotos(pin):
		global status
		status = True

	def main():
		global status
		GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=takePhotos)
		while True:
			if status:
				for i in range(5):
					GPIO.output(LedPin, GPIO.LOW)
					time.sleep(0.1)
					GPIO.output(LedPin, GPIO.HIGH)
					time.sleep(0.1)
				camera.capture(f'{user_home}/my_photo.jpg')
				print ('Take a photo!')          
				status = False
			else:
				GPIO.output(LedPin, GPIO.HIGH)
			time.sleep(1)

	def destroy():
		camera.stop_preview()
		GPIO.output(LedPin, GPIO.HIGH)
		GPIO.cleanup()

	if __name__ == '__main__':
		setup()
		try:
			main()
		except KeyboardInterrupt:
			destroy()

**Spiegazione del Codice**

.. code-block:: python

    GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=takePhotos)

Imposta l'evento per ``BtnPin``: quando viene premuto il pulsante (il segnale di livello cambia da alto a basso), chiama la funzione ``takePhotos()``.

.. code-block:: python

    def takePhotos(pin):
        global status
        status = True

Quando viene chiamata ``takePhotos()``, modifica lo stato in ``True``.

.. code-block:: python

    if status:
        for i in range(5):
            GPIO.output(LedPin, GPIO.LOW)
            time.sleep(0.1)
            GPIO.output(LedPin, GPIO.HIGH)
            time.sleep(0.1)
        camera.capture(f'{user_home}/my_photo.jpg')
        print ('Take a photo!')          
        status = False
    else:
        GPIO.output(LedPin, GPIO.HIGH)
    time.sleep(1)

Quando lo stato è ``True``, il Raspberry Pi farà lampeggiare il LED e scatterà una foto. La foto sarà nominata ``my_photo.jpg`` e salvata nella directory ``~``.

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

.. image:: ../img/4.1.1camera.JPG
   :align: center

