.. note::
¡Hola! Bienvenido a la comunidad de entusiastas de SunFounder Raspberry Pi, Arduino y ESP32 en Facebook. Profundiza en Raspberry Pi, Arduino y ESP32 con 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 vistas previas.
- **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.13_py:
4.1.13 Monitor de Sobrecalentamiento
=========================================
.. note::
.. image:: ../img/mcp3008_and_adc0834.jpg
:width: 25%
:align: left
Dependiendo de la versión de su kit, identifique si tiene **ADC0834** o **MCP3008** y continúe con la sección correspondiente.
Introducción
---------------------
Quizás quieras hacer un dispositivo de monitoreo de sobrecalentamiento
que se aplique a diversas situaciones, por ejemplo, en la fábrica, si
queremos tener una alarma y el apagado automático oportuno de la máquina
cuando hay un sobrecalentamiento del circuito. En este proyecto, utilizaremos
un termistor, un joystick, un zumbador, un LED y una pantalla LCD para hacer
un dispositivo inteligente de monitoreo de temperatura cuyo umbral es ajustable.
Componentes Necesarios
------------------------------
En este proyecto, necesitamos los siguientes componentes.
.. image:: ../img/list_Overheat_Monitor.png
:align: center
Es definitivamente conveniente comprar un kit completo, aquí está el enlace:
.. list-table::
:widths: 20 20 20
:header-rows: 1
* - Nombre
- ARTÍCULOS EN ESTE KIT
- ENLACE
* - Kit Raphael
- 337
- |link_Raphael_kit|
También puedes comprarlos por separado desde 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_led`
- |link_led_buy|
* - :ref:`cpn_joystick`
- \-
* - :ref:`cpn_adc0834`
- \-
* - :ref:`cpn_transistor`
- |link_transistor_buy|
* - :ref:`cpn_i2c_lcd`
- |link_i2clcd1602_buy|
* - :ref:`cpn_thermistor`
- |link_thermistor_buy|
* - :ref:`cpn_buzzer`
- \-
Diagrama Esquemático
--------------------------
============ ======== ======== ===
T-Board Name physical wiringPi BCM
GPIO17 Pin 11 0 17
GPIO18 Pin 12 1 18
GPIO27 Pin 13 2 27
GPIO22 Pin15 3 22
GPIO23 Pin16 4 23
GPIO24 Pin18 5 24
SDA1 Pin 3
SCL1 Pin 5
============ ======== ======== ===
.. image:: ../img/Schematic_three_one8.png
:align: center
Procedimientos Experimentales
-----------------------------
**Paso 1:** Construir el circuito.
.. image:: ../img/image258.png
**Paso 2**: Ir a la carpeta del código.
.. raw:: html
.. code-block::
cd ~/raphael-kit/python/
**Paso 3**: Ejecutar el archivo ejecutable.
.. raw:: html
.. code-block::
sudo python3 4.1.13_OverheatMonitor.py
Al ejecutar el código, la temperatura actual y el umbral de alta temperatura **40**
se muestran en el **I2C LCD1602**. Si la temperatura actual es mayor que el umbral,
el zumbador y el LED se activan para alertarte.
**Joystick** se utiliza aquí para ajustar el umbral de alta temperatura. Mover el **Joystick**
en la dirección del eje X y el eje Y puede ajustar (aumentar o disminuir) el umbral de alta
temperatura actual. Presiona el **Joystick** una vez más para restablecer el umbral al valor inicial.
.. note::
* Si obtienes el error ``FileNotFoundError: [Errno 2] No such file or directory: '/dev/i2c-1'``, necesitas consultar :ref:`i2c_config` para habilitar el I2C.
* Si obtienes el error ``ModuleNotFoundError: No module named 'smbus2'``, por favor ejecuta ``sudo apt install python3-smbus2``.
* Si aparece el error ``OSError: [Errno 121] Remote I/O error``, significa que el módulo está mal conectado o está roto.
* Si el código y el cableado están bien, pero la LCD aún no muestra contenido, puedes girar el potenciómetro en la parte posterior para aumentar el contraste.
**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
#!/usr/bin/env python3
import LCD1602
import RPi.GPIO as GPIO
import ADC0834
import time
import math
Joy_BtnPin = 22
buzzPin = 23
ledPin = 24
upperTem = 40
def setup():
ADC0834.setup()
GPIO.setmode(GPIO.BCM)
GPIO.setup(ledPin, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(buzzPin, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(Joy_BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
LCD1602.init(0x27, 1)
def get_joystick_value():
x_val = ADC0834.getResult(1)
y_val = ADC0834.getResult(2)
if(x_val > 200):
return 1
elif(x_val < 50):
return -1
elif(y_val > 200):
return -10
elif(y_val < 50):
return 10
else:
return 0
def upper_tem_setting():
global upperTem
LCD1602.write(0, 0, 'Upper Adjust: ')
change = int(get_joystick_value())
upperTem = upperTem + change
strUpperTem = str(upperTem)
LCD1602.write(0, 1, strUpperTem)
LCD1602.write(len(strUpperTem),1, ' ')
time.sleep(0.1)
def temperature():
analogVal = ADC0834.getResult()
Vr = 5 * float(analogVal) / 255
Rt = 10000 * Vr / (5 - Vr)
temp = 1/(((math.log(Rt / 10000)) / 3950) + (1 / (273.15+25)))
Cel = temp - 273.15
Fah = Cel * 1.8 + 32
return round(Cel,2)
def monitoring_temp():
global upperTem
Cel=temperature()
LCD1602.write(0, 0, 'Temp: ')
LCD1602.write(0, 1, 'Upper: ')
LCD1602.write(6, 0, str(Cel))
LCD1602.write(7, 1, str(upperTem))
time.sleep(0.1)
if Cel >= upperTem:
GPIO.output(buzzPin, GPIO.HIGH)
GPIO.output(ledPin, GPIO.HIGH)
else:
GPIO.output(buzzPin, GPIO.LOW)
GPIO.output(ledPin, GPIO.LOW)
def loop():
lastState=1
stage=0
while True:
currentState=GPIO.input(Joy_BtnPin)
if currentState==1 and lastState ==0:
stage=(stage+1)%2
time.sleep(0.1)
LCD1602.clear()
lastState=currentState
if stage == 1:
upper_tem_setting()
else:
monitoring_temp()
def destroy():
LCD1602.clear()
ADC0834.destroy()
GPIO.cleanup()
if __name__ == '__main__': # Program start from here
try:
setup()
while True:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the program destroy() will be executed.
destroy()
**Explicación del Código**
.. code-block:: python
def get_joystick_value():
x_val = ADC0834.getResult(1)
y_val = ADC0834.getResult(2)
if(x_val > 200):
return 1
elif(x_val < 50):
return -1
elif(y_val > 200):
return -10
elif(y_val < 50):
return 10
else:
return 0
Esta función lee los valores de X e Y. Si **X > 200**, devolverá “\ **1**\ ”; si **X < 50**,
devolverá “\ **-1**\ ”; si **Y > 200**, devolverá “\ **-10**\ ”, y si **Y < 50**, devolverá
“\ **10**\ ”.
.. code-block:: python
def upper_tem_setting():
global upperTem
LCD1602.write(0, 0, 'Upper Adjust: ')
change = int(get_joystick_value())
upperTem = upperTem + change
LCD1602.write(0, 1, str(upperTem))
LCD1602.write(len(strUpperTem),1, ' ')
time.sleep(0.1)
Esta función ajusta el umbral y lo muestra en la pantalla I2C LCD1602.
.. code-block:: python
def temperature():
analogVal = ADC0834.getResult()
Vr = 5 * float(analogVal) / 255
Rt = 10000 * Vr / (5 - Vr)
temp = 1/(((math.log(Rt / 10000)) / 3950) + (1 / (273.15+25)))
Cel = temp - 273.15
Fah = Cel * 1.8 + 32
return round(Cel,2)
Lee el valor analógico del **CH0** (termistor) del **ADC0834** y luego lo convierte en un valor de temperatura.
.. code-block:: python
def monitoring_temp():
global upperTem
Cel=temperature()
LCD1602.write(0, 0, 'Temp: ')
LCD1602.write(0, 1, 'Upper: ')
LCD1602.write(6, 0, str(Cel))
LCD1602.write(7, 1, str(upperTem))
time.sleep(0.1)
if Cel >= upperTem:
GPIO.output(buzzPin, GPIO.HIGH)
GPIO.output(ledPin, GPIO.HIGH)
else:
GPIO.output(buzzPin, GPIO.LOW)
GPIO.output(ledPin, GPIO.LOW)
Cuando el código se ejecuta, la temperatura actual y el umbral de alta
temperatura **40** se muestran en la **I2C LCD1602**. Si la temperatura
actual es mayor que el umbral, el buzzer y el LED se activan para alertarte.
.. code-block:: python
def loop():
lastState=1
stage=0
while True:
currentState=GPIO.input(Joy_BtnPin)
if currentState==1 and lastState ==0:
stage=(stage+1)%2
time.sleep(0.1)
LCD1602.clear()
lastState=currentState
if stage == 1:
upper_tem_setting()
else:
monitoring_temp()
La función ``loop()`` contiene el proceso completo del programa como se muestra:
1) Cuando el programa comienza, el valor inicial de **stage** es **0**, y la temperatura
actual y el umbral de alta temperatura **40** se muestran en la **I2C LCD1602**. Si la
temperatura actual es mayor que el umbral, el buzzer y el LED se activan para alertarte.
2) Presiona el joystick, y **stage** será **1**, pudiendo ajustar el umbral de alta
temperatura. Mover el joystick en la dirección del eje X e Y ajusta (aumenta o disminuye)
el umbral de alta temperatura actual. Presiona nuevamente el joystick para restablecer el
umbral al valor inicial.
Imagen del Fenómeno
-------------------------
.. image:: ../img/image259.jpeg
:align: center