.. note:: Hola, ¡bienvenido a la comunidad de entusiastas de SunFounder Raspberry Pi, Arduino y ESP32 en Facebook! Sumérgete más profundamente en Raspberry Pi, Arduino y ESP32 junto a otros entusiastas. **¿Por qué unirse?** - **Soporte experto**: Resuelve problemas postventa 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**: Accede anticipadamente a nuevos anuncios de 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 navideñas. 👉 ¿Listo para explorar y crear con nosotros? Haz clic en [|link_sf_facebook|] y únete hoy mismo. .. _4.1.3_py: 4.1.3 Reloj Parlante ============================= Introducción ----------------- En este proyecto, vamos a hacer un reloj parlante con un altavoz y un display de 7 segmentos de 4 dígitos. El display mostrará la hora y el altavoz anunciará la hora cada hora. Componentes Necesarios ------------------------------ En este proyecto, necesitamos los siguientes componentes. .. image:: ../img/3.1.17components.png :width: 800 :align: center Es muy conveniente comprar un kit completo, aquí está el enlace: .. list-table:: :widths: 20 20 20 :header-rows: 1 * - Nombre - ELEMENTOS EN ESTE KIT - ENLACE * - Kit Raphael - 337 - |link_Raphael_kit| También puedes comprarlos por separado en los enlaces a continuación. .. list-table:: :widths: 30 20 :header-rows: 1 * - INTRODUCCIÓN DEL COMPONENTE - ENLACE DE COMPRA * - :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_audio_speaker` - \- * - :ref:`cpn_4_digit` - \- * - :ref:`cpn_74hc595` - |link_74hc595_buy| Diagrama Esquemático -------------------------- ============== =============== ======== === Nombre T-Board cableado físico 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 ============== =============== ======== === .. image:: ../img/4.1.3_speechclock_schematic.png :width: 700 :align: center .. image:: ../img/3.1.17_schematic.png :width: 400 :align: center Procedimientos Experimentales ------------------------------- **Paso 1:** Construye el circuito. .. image:: ../img/3.1.17fritzing.png :width: 900 :align: center Antes de este proyecto, debes asegurarte de haber completado :ref:`3.1.4_py`. **Paso 2:** Usa el comando ``date`` para ver la hora local. .. raw:: html .. code-block:: date Si la hora local es diferente de la hora real, necesitas usar el siguiente comando para configurar la zona horaria. .. raw:: html .. code-block:: sudo dpkg-reconfigure tzdata Elige tu zona horaria. .. image:: ../img/tzdata.png **Paso 3:** Accede a la carpeta del código. .. raw:: html .. code-block:: cd ~/raphael-kit/python/ **Paso 4:** Ejecuta. .. raw:: html .. code-block:: python3 4.1.3_SpeechClock.py Después de ejecutar el código: - Se reproduce un mensaje de bienvenida: “Clock system started. Welcome!” - La pantalla de cuatro dígitos muestra la hora actual en formato HH:MM. - Al inicio de cada hora (cuando el minuto = 0), el sistema anuncia la hora actual una vez. - La pantalla se actualiza continuamente hasta que se presione ``Ctrl+C``, momento en el cual se liberan los recursos de GPIO. **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 .. code-block:: python import RPi.GPIO as GPIO from tts import TTS import time # Initialize TTS tts = TTS(engine="espeak") tts.lang('en-US') # GPIO pins SDI = 24 RCLK = 23 SRCLK = 25 placePin = (10, 22, 27, 17) # Seven-segment encoding number = (0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90) def setup(): GPIO.setmode(GPIO.BCM) GPIO.setup(SDI, GPIO.OUT) GPIO.setup(RCLK, GPIO.OUT) GPIO.setup(SRCLK, GPIO.OUT) for pin in placePin: GPIO.setup(pin, GPIO.OUT) def clearDisplay(): for _ 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): # Turn all digits off for pin in placePin: GPIO.output(pin, GPIO.LOW) # Turn selected digit ON GPIO.output(placePin[digit], GPIO.HIGH) def loop(): status = 0 while True: now = time.localtime() hour = now.tm_hour minute = now.tm_min # Display minute (unit) clearDisplay() pickDigit(0) hc595_shift(number[minute % 10]) # Display minute (tens) clearDisplay() pickDigit(1) hc595_shift(number[(minute // 10) % 10]) # Display hour (unit) clearDisplay() pickDigit(2) hc595_shift(number[hour % 10]) # Display hour (tens) clearDisplay() pickDigit(3) hc595_shift(number[(hour // 10) % 10]) # Speak once every hour (at minute == 0) if minute == 0 and status == 0: tts.say(f'The time is now {hour} hours and {minute} minutes') time.sleep(3) # Give time to finish speaking status = 1 elif minute != 0: status = 0 time.sleep(0.005) # Prevent CPU overload def destroy(): GPIO.cleanup() if __name__ == '__main__': setup() # ★ Welcome message at startup tts.say("Clock system started. Welcome!") time.sleep(3) try: loop() except KeyboardInterrupt: destroy() **Explicación del código** #. Inicializa el motor de conversión de texto a voz (TTS) usando ``espeak`` y establece el idioma en inglés. .. code-block:: python tts = TTS(engine="espeak") tts.lang('en-US') #. Define los pines GPIO utilizados para el registro de desplazamiento (74HC595) y los pines de selección de dígitos para la pantalla de 4 dígitos. .. code-block:: python SDI = 24 RCLK = 23 SRCLK = 25 placePin = (10, 22, 27, 17) #. Almacena los valores de codificación de segmentos usados para mostrar los dígitos 0–9 en la pantalla de siete segmentos. .. code-block:: python number = (0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90) #. Limpia la pantalla enviando ocho bits “1” al registro de desplazamiento. .. code-block:: python def clearDisplay(): for _ 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) #. Envía un byte de datos de segmento al 74HC595 para actualizar el dígito mostrado. .. code-block:: python 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) #. Selecciona una de las cuatro posiciones de dígito (miles, centenas, decenas, unidades) para realizar el multiplexado. .. code-block:: python def pickDigit(digit): for pin in placePin: GPIO.output(pin, GPIO.LOW) GPIO.output(placePin[digit], GPIO.HIGH) #. Lee la hora actual desde el reloj del sistema. .. code-block:: python now = time.localtime() hour = now.tm_hour minute = now.tm_min #. Actualiza cada dígito de la pantalla de siete segmentos para mostrar la hora actual en formato HH:MM. .. code-block:: python hc595_shift(number[minute % 10]) hc595_shift(number[(minute // 10) % 10]) hc595_shift(number[hour % 10]) hc595_shift(number[(hour // 10) % 10]) #. Pronuncia la hora actual al inicio de cada hora usando TTS. .. code-block:: python if minute == 0 and status == 0: tts.say(f'The time is now {hour} hours and {minute} minutes') status = 1 elif minute != 0: status = 0 #. Reproduce un mensaje de bienvenida cuando el programa inicia. .. code-block:: python tts.say("Clock system started. Welcome!") #. Libera todos los pines GPIO cuando el usuario detiene el programa con ``Ctrl+C``. .. code-block:: python GPIO.cleanup() Imagen del Fenómeno ------------------------ .. image:: ../img/4.1.3speech_clock.JPG :align: center