.. note::

    ¡Hola! Bienvenido a la Comunidad de Entusiastas de SunFounder Raspberry Pi & Arduino & ESP32 en Facebook. Profundiza en Raspberry Pi, Arduino y ESP32 con otros entusiastas.

    **¿Por qué unirse?**

    - **Soporte Experto**: Resuelve problemas post-venta y desafíos técnicos con la ayuda de nuestra comunidad y equipo.
    - **Aprender y Compartir**: Intercambia consejos y tutoriales para mejorar tus habilidades.
    - **Avances Exclusivos**: Obtén acceso anticipado a anuncios de nuevos productos y adelantos exclusivos.
    - **Descuentos Especiales**: Disfruta de descuentos exclusivos en nuestros productos más recientes.
    - **Promociones y Sorteos Festivos**: Participa en sorteos y promociones durante las festividades.

    👉 ¿Listo para explorar y crear con nosotros? Haz clic en [|link_sf_facebook|] y únete hoy mismo!

.. _4.1.18_py:


4.1.18 JUEGO - 10 Segundos
===================================

Introducción
-------------------

A continuación, sigue conmigo para hacer un dispositivo de juego que desafíe tu concentración. 
Ata el interruptor de inclinación a una vara para hacer una varita mágica. Agita la varita, 
el display de 4 dígitos comenzará a contar, agítala de nuevo y dejará de contar. Si logras 
mantener el conteo mostrado en **10.00**, entonces ganas. Puedes jugar con tus amigos para 
ver quién es el mago del tiempo.


Componentes Requeridos
------------------------------

En este proyecto, necesitamos los siguientes componentes.

.. image:: ../img/list_GAME_10_Second.png
    :align: center

Es definitivamente conveniente comprar un kit completo, aquí está el enlace:

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

    *   - Nombre	
        - ITEMS IN THIS KIT
        - ENLACE
    *   - Raphael Kit
        - 337
        - |link_Raphael_kit|

También puedes comprarlos por separado en los siguientes enlaces.

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

    *   - INTRODUCCIÓN DEL COMPONENTE
        - ENLACE DE COMPRA

    *   - :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_4_digit`
        - \-
    *   - :ref:`cpn_74hc595`
        - |link_74hc595_buy|
    *   - :ref:`cpn_tilt_switch`
        - \-

Diagrama Esquemático
------------------------

================== ======== ======== ===
Nombre del T-Board physical wiringPi BCM
GPIO17             Pin 11   0        17
GPIO27             Pin 13   2        27
GPIO22             Pin 15   3        22
SPIMOSI            Pin 19   12       10
GPIO18             Pin 12   1        18
GPIO23             Pin 16   4        23
GPIO24             Pin 18   5        24
GPIO26             Pin 37   25       26
================== ======== ======== ===

.. image:: ../img/Schematic_three_one13.png
   :align: center

Procedimientos Experimentales
-----------------------------------

**Paso 1**: Construir el circuito.

.. image:: ../img/image277.png

**Paso 2**: Ir a la carpeta del código.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python/

**Paso 3**: Ejecutar el archivo ejecutable.

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 4.1.18_GAME_10Second.py

Agita la varita, el display de 4 dígitos comenzará a contar, agítala de nuevo 
y dejará de contar. Si logras mantener el conteo mostrado en **10.00**, entonces 
ganas. Agítala una vez más para comenzar la siguiente ronda del juego.

**Código**

.. note::
    Puedes **Modificar/Restablecer/Copiar/Ejecutar/Detener** el código a continuación. Pero antes de eso, necesitas ir a la ruta del código fuente como ``raphael-kit/python``. Después de modificar el código, puedes ejecutarlo directamente para ver el efecto.

.. raw:: html

    <run></run>

.. code-block:: python

    #!/usr/bin/env python3
    import RPi.GPIO as GPIO
    import time
    import threading

    sensorPin = 26

    SDI = 24
    RCLK = 23
    SRCLK = 18

    placePin = (10, 22, 27, 17)
    number = (0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90)

    counter = 0
    timer =0
    gameState =0

    def clearDisplay():
        for i in range(8):
            GPIO.output(SDI, 1)
            GPIO.output(SRCLK, GPIO.HIGH)
            GPIO.output(SRCLK, GPIO.LOW)
        GPIO.output(RCLK, GPIO.HIGH)
        GPIO.output(RCLK, GPIO.LOW)

    def hc595_shift(data):
        for i in range(8):
            GPIO.output(SDI, 0x80 & (data << i))
            GPIO.output(SRCLK, GPIO.HIGH)
            GPIO.output(SRCLK, GPIO.LOW)
        GPIO.output(RCLK, GPIO.HIGH)
        GPIO.output(RCLK, GPIO.LOW)

    def pickDigit(digit):
        for i in placePin:
            GPIO.output(i,GPIO.LOW)
        GPIO.output(placePin[digit], GPIO.HIGH)

    def display():
        global counter
        clearDisplay()
        pickDigit(0)
        hc595_shift(number[counter % 10])

        clearDisplay()
        pickDigit(1)
        hc595_shift(number[counter % 100//10])

        clearDisplay()
        pickDigit(2)
        hc595_shift(number[counter % 1000//100]-0x80)

        clearDisplay()
        pickDigit(3)
        hc595_shift(number[counter % 10000//1000])

    def stateChange():
        global gameState
        global counter
        global timer1
        if gameState == 0:
            counter = 0
            time.sleep(1)
            timer()
        elif gameState ==1:
            timer1.cancel()
            time.sleep(1)
        gameState = (gameState+1)%2

    def loop():
        global counter
        currentState = 0
        lastState = 0
        while True:
            display()
            currentState=GPIO.input(sensorPin)
            if (currentState == 0) and (lastState == 1):
                stateChange()
            lastState=currentState

    def timer():
        global counter
        global timer1
        timer1 = threading.Timer(0.01, timer)
        timer1.start()
        counter += 1

    def setup():
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(SDI, GPIO.OUT)
        GPIO.setup(RCLK, GPIO.OUT)
        GPIO.setup(SRCLK, GPIO.OUT)
        for i in placePin:
            GPIO.setup(i, GPIO.OUT)
        GPIO.setup(sensorPin, GPIO.IN)

    def destroy():   # When "Ctrl+C" is pressed, the function is executed.
        GPIO.cleanup()
        global timer1
        timer1.cancel()

    if __name__ == '__main__':  # Program starting from here
        setup()
        try:
            loop()
        except KeyboardInterrupt:
            destroy()

**Explicación del Código**

.. code-block:: python

    def stateChange():
        global gameState
        global counter
        global timer1
        if gameState == 0:
            counter = 0
            time.sleep(1)
            timer() 
        elif gameState ==1:
            timer1.cancel()
            time.sleep(1)
        gameState = (gameState+1)%2

El juego se divide en dos modos:

``gameState==0`` es el modo "inicio", en el cual se mide el tiempo y se
muestra en el display de segmentos. Al agitar el interruptor de inclinación,
se entra en el modo "mostrar".

``gameState==1`` es el modo "mostrar", que detiene el cronometraje y muestra el
tiempo en el display de segmentos. Al agitar el interruptor de inclinación
nuevamente, se reinicia el temporizador y se reinicia el juego.

.. code-block:: python

    def loop():
        global counter
        currentState = 0
        lastState = 0
        while True:
            display()
            currentState=GPIO.input(sensorPin)
            if (currentState == 0) and (lastState == 1):
                stateChange()
            lastState=currentState

``loop()`` es la función principal. Primero, el tiempo se muestra en el display
de segmentos de 4 dígitos y se lee el valor del interruptor de inclinación. Si
el estado del interruptor de inclinación ha cambiado, se llama a
``stateChange()``.

.. code-block:: python

    def timer():  
        global counter
        global timer1
        timer1 = threading.Timer(0.01, timer) 
        timer1.start()  
        counter += 1

Después de que el intervalo alcanza 0.01s, se llama a la función del
temporizador; se suma 1 a counter, y se usa el temporizador nuevamente para
ejecutarse repetidamente cada 0.01s.

Imagen del Fenómeno
-----------------------

.. image:: ../img/image278.jpeg
   :align: center



