.. note::
Bonjour et bienvenue dans la Communauté Facebook des passionnés de Raspberry Pi, Arduino et ESP32 de SunFounder ! Plongez plus profondément dans l'univers des 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** : Accédez en avant-première aux annonces de nouveaux produits et aux aperçus.
- **Réductions spéciales** : Profitez de réductions exclusives sur nos produits les plus récents.
- **Promotions festives et cadeaux** : Participez à des cadeaux et des promotions de vacances.
👉 Prêt à explorer et à créer avec nous ? Cliquez [|link_sf_facebook|] et rejoignez-nous aujourd'hui !
.. _2.2.4_py_pi5:
2.2.4 Module à interrupteur Reed
===================================
Introduction
---------------
Dans ce projet, nous allons apprendre à connaître l'interrupteur Reed, qui est un interrupteur électrique fonctionnant par le biais d'un champ magnétique appliqué.
Composants nécessaires
--------------------------
Dans ce projet, nous avons besoin des composants suivants.
.. image:: ../python_pi5/img/2.2.4_reed_switch_list.png
:width: 700
:align: center
Il est certainement pratique d'acheter un kit complet, voici le lien :
.. list-table::
:widths: 20 20 20
:header-rows: 1
* - Nom
- ARTICLES 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_reed_switch`
- |link_reed_switch_buy|
Schéma
---------
============ ======== ======== ===
Nom T-Board physique wiringPi BCM
GPIO17 Pin 11 0 17
GPIO27 Pin 13 2 27
GPIO22 Pin 15 3 22
============ ======== ======== ===
.. image:: ../python_pi5/img/2.2.4_reed_switch_schematic_1.png
:width: 400
:align: center
.. image:: ../python_pi5/img/2.2.4_reed_switch_schematic_2.png
:width: 400
:align: center
Procédures expérimentales
-----------------------------
**Étape 1 :** Construisez le circuit.
.. image:: ../python_pi5/img/2.2.4_reed_switch_circuit.png
:width: 700
:align: center
**Étape 2 :** Changez de répertoire.
.. raw:: html
.. code-block::
cd ~/raphael-kit/python-pi5
**Étape 3 :** Exécutez.
.. raw:: html
.. code-block::
sudo python3 2.2.4_ReedSwitch_zero.py
La LED verte s'allume lorsque le code est exécuté. Si un aimant est placé près du module à interrupteur Reed, la LED rouge s'allume ; retirez l'aimant et la LED verte se rallume.
.. warning::
Si vous recevez le message d'erreur ``RuntimeError: Cannot determine SOC peripheral base address``, veuillez consulter :ref:`faq_soc`
**Code**
.. note::
Vous pouvez **Modifier/Réinitialiser/Copier/Exécuter/Arrêter** le code ci-dessous. Mais avant cela, vous devez vous rendre au chemin du code source comme ``raphael-kit/python-pi5``. Après avoir modifié le code, vous pouvez l'exécuter directement pour voir l'effet.
.. raw:: html
.. code-block:: python
#!/usr/bin/env python3
from gpiozero import LED, Button
# Initialize the reed switch and LEDs using GPIO Zero
reed_switch = Button(17, pull_up=True) # Reed switch on GPIO 17, using an internal pull-up resistor
green_led = LED(27) # Green LED connected to GPIO pin 27
red_led = LED(22) # Red LED connected to GPIO pin 22
def update_leds():
"""
Update the state of the LEDs based on the reed switch.
Turns the red LED on and green LED off when the reed switch is pressed, and vice versa.
"""
if reed_switch.is_pressed:
green_led.off() # Turn off the green LED
red_led.on() # Turn on the red LED
else:
green_led.on() # Turn on the green LED
red_led.off() # Turn off the red LED
try:
green_led.on() # Turn on the green LED at the start
while True:
# Set the callback functions for reed switch state changes
reed_switch.when_pressed = update_leds # Callback when the switch is pressed
reed_switch.when_released = update_leds # Callback when the switch is released
except KeyboardInterrupt:
# Clean up resources and exit on Ctrl+C
green_led.off()
red_led.off()
pass
**Explication du code**
#. Cette ligne spécifie que le script doit être exécuté en utilisant Python 3. Elle importe les classes ``LED`` et ``Button`` (utilisées pour l'interrupteur Reed) de la bibliothèque gpiozero.
.. code-block:: python
#!/usr/bin/env python3
from gpiozero import LED, Button
#. Initialise l'interrupteur Reed sur la broche GPIO 17 avec une résistance pull-up interne. Initialise également deux LED connectées aux broches GPIO 27 et 22.
.. code-block:: python
# Initialize the reed switch and LEDs using GPIO Zero
reed_switch = Button(17, pull_up=True) # Reed switch on GPIO 17, using an internal pull-up resistor
green_led = LED(27) # Green LED connected to GPIO pin 27
red_led = LED(22) # Red LED connected to GPIO pin 22
#. Définit la fonction ``update_leds``, qui met à jour l'état des LED en fonction de l'état de l'interrupteur Reed. La LED rouge s'allume et la LED verte s'éteint lorsque l'interrupteur est pressé, et l'inverse lorsqu'il est relâché.
.. code-block:: python
def update_leds():
if reed_switch.is_pressed:
green_led.off() # Turn off the green LED
red_led.on() # Turn on the red LED
else:
green_led.on() # Turn on the green LED
red_led.off() # Turn off the red LED
#. Définit l'état initial de la LED verte à allumé. La boucle principale assigne la fonction ``update_leds`` comme callbacks pour les événements ``when_pressed`` et ``when_released`` de l'interrupteur Reed. Inclut une gestion des exceptions pour KeyboardInterrupt afin de nettoyer et quitter le programme proprement.
.. code-block:: python
try:
green_led.on() # Turn on the green LED at the start
while True:
# Set the callback functions for reed switch state changes
reed_switch.when_pressed = update_leds # Callback when the switch is pressed
reed_switch.when_released = update_leds # Callback when the switch is released
except KeyboardInterrupt:
# Clean up resources and exit on Ctrl+C
green_led.off()
red_led.off()
pass