.. note::
Bonjour et bienvenue dans la communauté SunFounder Raspberry Pi & Arduino & ESP32 sur Facebook !
Plongez plus profondément dans l’univers Raspberry Pi, Arduino et ESP32 avec d’autres passionnés.
**Pourquoi rejoindre ?**
- **Support d’experts :** Résolvez les problèmes après‑vente et les défis techniques avec l’aide de notre communauté et de notre équipe.
- **Apprendre et partager :** Échangez des astuces et des tutoriels pour améliorer vos compétences.
- **Aperçus exclusifs :** Obtenez un accès anticipé aux annonces de nouveaux produits et aux avant‑premières.
- **Réductions spéciales :** Profitez de remises exclusives sur nos derniers produits.
- **Promotions et concours festifs :** Participez à des concours et promotions de vacances.
👉 Prêt à explorer et créer avec nous ? Cliquez sur [|link_sf_facebook|] et rejoignez‑nous dès aujourd’hui !
.. _4.1.13_py_mcp3008:
4.1.13 Moniteur de surchauffe (MCP3008)
=======================================
.. note::
.. image:: ../img/mcp3008_and_adc0834.jpg
:width: 25%
:align: left
Selon la version de votre kit, veuillez identifier si vous avez **ADC0834** ou **MCP3008** et suivre la section correspondante.
Introduction
------------
Vous pourriez vouloir réaliser un dispositif de surveillance de surchauffe applicable à différentes situations,
par exemple, dans une usine, pour déclencher une alarme et arrêter automatiquement une machine lorsqu’un circuit surchauffe.
Dans ce projet, nous allons utiliser un thermistor, un joystick, un buzzer, une LED et un écran LCD pour créer
un dispositif intelligent de surveillance de la température dont le seuil est ajustable.
Composants requis
-----------------
Dans ce projet, nous avons besoin des composants suivants :
.. image:: ../img/list2_Overheat_Monitor.png
:width: 800
:align: center
Il est évidemment plus pratique d’acheter un kit complet, voici le lien :
.. list-table::
:widths: 20 20 20
:header-rows: 1
* - Nom
- ÉLÉMENTS DANS CE KIT
- LIEN
* - Kit Raphael
- 337
- |link_Raphael_kit|
Vous pouvez également les acheter séparément via les liens ci‑dessous :
.. list-table::
:widths: 30 20
:header-rows: 1
* - INTRODUCTION DU COMPOSANT
- LIEN D’ACHAT
* - :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_joystick`
- \-
* - :ref:`cpn_mcp3008`
- \-
* - :ref:`cpn_transistor`
- |link_transistor_buy|
* - :ref:`cpn_i2c_lcd`
- |link_i2clcd1602_buy|
* - :ref:`cpn_thermistor`
- |link_thermistor_buy|
* - :ref:`cpn_buzzer`
- \-
Schéma
------
============ ======== ======== ===
Nom T‑Board physique WiringPi BCM
SPICE0 Pin 24 10 8
SPIMOSI Pin 19 12 10
SPISIMO Pin 21 13 9
SPISCLK Pin 23 14 11
GPIO22 Pin 15 3 22
GPIO23 Pin 16 4 23
GPIO24 Pin 18 5 24
SDA1 Pin 3
SCL1 Pin 5
============ ======== ======== ===
.. image:: ../img/schematic_over_monitor_mcp3008.png
:align: center
Procédure expérimentale
-----------------------
**Étape 1 :** Construire le circuit.
.. image:: ../img/july24_3.1.8_overheat_monitor_mcp3008.png
**Étape 2 :** Configurer l’interface SPI et installer la bibliothèque ``spidev`` (voir :ref:`spi_configuration` pour des instructions détaillées).
Si vous avez déjà effectué ces étapes, vous pouvez les ignorer.
**Étape 3 :** Accéder au dossier du code.
.. raw:: html
.. code-block::
cd ~/raphael-kit/python
**Étape 4 :** Exécuter le fichier.
.. raw:: html
.. code-block::
sudo python3 4.1.13-2_OverheatMonitor.py
Lorsque le code s’exécute, la température actuelle et le seuil haute température **40** s’affichent sur l’écran **I2C LCD1602**.
Si la température dépasse le seuil, le buzzer et la LED se déclenchent pour vous alerter.
Le **joystick** permet d’ajuster le seuil de température maximale : déplacer le joystick selon les axes X et Y augmente ou diminue ce seuil.
Appuyer sur le joystick réinitialise le seuil à sa valeur initiale.
.. note::
* Si vous obtenez l’erreur ``FileNotFoundError: [Errno 2] No such file or directory: '/dev/i2c-1'``, reportez‑vous à :ref:`i2c_config` pour activer l’I2C.
* Si l’erreur ``ModuleNotFoundError: No module named 'smbus2'`` apparaît, exécutez : ``sudo apt install python3-smbus2``.
* Si l’erreur ``OSError: [Errno 121] Remote I/O error`` se produit, cela signifie que le module est mal câblé ou défectueux.
* Si le code et le câblage sont corrects, mais que l’écran LCD n’affiche toujours rien, ajustez le potentiomètre à l’arrière pour augmenter le contraste.
.. warning::
Si un message d’erreur ``RuntimeError: Cannot determine SOC peripheral base address`` s’affiche, reportez‑vous à :ref:`faq_soc`.
Code
----
.. note::
Vous pouvez **Modifier/Réinitialiser/Copier/Exécuter/Arrêter** le code ci‑dessous.
Mais avant cela, vous devez aller dans le chemin du code source comme ``raphael-kit/python``.
Après modification, vous pouvez exécuter directement le code pour voir l’effet.
.. raw:: html
.. code-block:: python
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import spidev
import time
import math
import LCD1602
JOY_BTN_PIN = 22 # Broche bouton
BUZZER_PIN = 23 # Broche buzzer
LED_PIN = 24 # Broche LED
GPIO.setmode(GPIO.BCM)
GPIO.setup(JOY_BTN_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.setup(LED_PIN, GPIO.OUT)
upperTem = 40
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1000000
LCD1602.init(0x27, 1)
def read_adc(channel):
if channel < 0 or channel > 7:
return -1
adc = spi.xfer2([1, (8 + channel) << 4, 0])
return ((adc[1] & 0x03) << 8) | adc[2]
def get_joystick_value():
x_val = read_adc(1)
y_val = read_adc(2)
if x_val > 800:
return 1
elif x_val < 200:
return -1
elif y_val > 800:
return -10
elif y_val < 200:
return 10
else:
return 0
def upper_tem_setting():
global upperTem
LCD1602.write(0, 0, 'Upper Adjust: ')
change = int(get_joystick_value())
upperTem += change
LCD1602.write(0, 1, str(upperTem))
LCD1602.write(len(str(upperTem)), 1, ' ')
time.sleep(0.1)
def temperature():
analogVal = read_adc(0)
Vr = 3.3 * analogVal / 1023.0
if Vr == 0:
return 0
Rt = 10000.0 * (3.3 - Vr) / Vr
tempK = 1.0 / (((math.log(Rt / 10000.0)) / 3950.0) + (1.0 / (273.15 + 25.0)))
return round(tempK - 273.15, 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(BUZZER_PIN, GPIO.HIGH)
GPIO.output(LED_PIN, GPIO.HIGH)
else:
GPIO.output(BUZZER_PIN, GPIO.LOW)
GPIO.output(LED_PIN, GPIO.LOW)
try:
lastState = GPIO.input(JOY_BTN_PIN)
stage = 0
while True:
currentState = GPIO.input(JOY_BTN_PIN)
if currentState == GPIO.HIGH and lastState == GPIO.LOW:
stage = (stage + 1) % 2
time.sleep(0.1)
LCD1602.clear()
lastState = currentState
if stage == 1:
upper_tem_setting()
else:
monitoring_temp()
except KeyboardInterrupt:
pass
finally:
LCD1602.clear()
GPIO.cleanup()
spi.close()
Explication du code
-------------------
1. **Importation des bibliothèques** : GPIO pour le contrôle des broches, SPI pour l’ADC, LCD pour l’affichage, etc.
.. code-block:: python
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import spidev
import time
import math
import LCD1602
2. **Configuration des broches GPIO** : bouton du joystick, buzzer et LED.
.. code-block:: python
JOY_BTN_PIN = 22 # Button pin
BUZZER_PIN = 23 # Buzzer pin
LED_PIN = 24 # LED pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(JOY_BTN_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.setup(LED_PIN, GPIO.OUT)
3. **Initialisation du bus SPI et de l’écran LCD1602**.
.. code-block:: python
upperTem = 40
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1000000
LCD1602.init(0x27, 1)
4. **Lecture des valeurs analogiques (read_adc)** via MCP3008.
.. code-block:: python
def read_adc(channel):
if channel < 0 or channel > 7:
return -1
adc = spi.xfer2([1, (8 + channel) << 4, 0])
value = ((adc[1] & 0x03) << 8) | adc[2]
return value
5. **Lecture du joystick (get_joystick_value)** : ajuste le seuil selon le mouvement.
.. code-block:: python
def get_joystick_value():
x_val = read_adc(1)
y_val = read_adc(2)
if x_val > 800:
return 1
elif x_val < 200:
return -1
elif y_val > 800:
return -10
elif y_val < 200:
return 10
else:
return 0
6. **Réglage du seuil (upper_tem_setting)** et affichage sur l’écran.
.. code-block:: python
def upper_tem_setting():
global upperTem
LCD1602.write(0, 0, 'Upper Adjust: ')
change = int(get_joystick_value())
upperTem += change
strUpperTem = str(upperTem)
LCD1602.write(0, 1, strUpperTem)
LCD1602.write(len(strUpperTem), 1, ' ')
time.sleep(0.1)
7. **Lecture de la température (temperature)** : conversion tension → résistance → température via Steinhart‑Hart.
.. code-block:: python
def temperature():
analogVal = read_adc(0)
Vr = 3.3 * analogVal / 1023.0
if Vr == 0:
return 0
Rt = 10000.0 * (3.3 - Vr) / Vr
tempK = 1.0 / (((math.log(Rt / 10000.0)) / 3950.0) + (1.0 / (273.15 + 25.0)))
Cel = tempK - 273.15
return round(Cel, 2)
8. **Surveillance de la température (monitoring_temp)** : affichage et déclenchement du buzzer/LED si dépassement.
.. 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(BUZZER_PIN, GPIO.HIGH)
GPIO.output(LED_PIN, GPIO.HIGH)
else:
GPIO.output(BUZZER_PIN, GPIO.LOW)
GPIO.output(LED_PIN, GPIO.LOW)
9. **Boucle principale** : bascule entre le mode réglage et le mode surveillance par pression sur le joystick.
.. code-block:: python
try:
lastState = GPIO.input(JOY_BTN_PIN)
stage = 0
while True:
currentState = GPIO.input(JOY_BTN_PIN)
if currentState == GPIO.HIGH and lastState == GPIO.LOW:
stage = (stage + 1) % 2
time.sleep(0.1)
LCD1602.clear()
lastState = currentState
if stage == 1:
upper_tem_setting()
else:
monitoring_temp()
10. **Nettoyage final** : arrêt du SPI, libération des GPIO et effacement de l’écran LCD.
.. code-block:: python
except KeyboardInterrupt:
pass
finally:
LCD1602.clear()
GPIO.cleanup()
spi.close()