Raspberry Pi - Buzzer Piézo

Ce tutoriel vous explique comment utiliser le Raspberry Pi pour contrôler le buzzer piézoélectrique. En détail, nous apprendrons :

Préparation du matériel

1×Raspberry Pi 5
1×Buzzer piézo actif 3-24V
1×Module buzzer piézo actif
1×Module buzzer piézo passif
1×Plaque d'essai
1×Fils de connexion
1×Recommandé: Shield à bornier à vis pour Raspberry Pi
1×Recommandé: Kit plaque de base prototypage et plaque d'essai pour Raspberry Pi
1×Recommandé: Écran tactile HDMI pour Raspberry Pi

Ou vous pouvez acheter les kits suivants:

1×Kit de Capteurs DIYables (30 capteurs/écrans)
1×Kit de Capteurs DIYables (18 capteurs/écrans)
Divulgation : Certains des liens fournis dans cette section sont des liens affiliés Amazon. Nous pouvons recevoir une commission pour tout achat effectué via ces liens, sans coût supplémentaire pour vous. Nous vous remercions de votre soutien.

À propos du buzzer piézoélectrique

Un buzzer piézoélectrique est utilisé pour produire du son, des bips ou même une mélodie à partir d'une chanson.

Disponible sur le marché, un buzzer actif 3V-24V qui sert à deux fins : fonctionnant à la fois comme un buzzer actif 3-5V et comme un buzzer haute tension (12V et plus).

  • Connecter ce buzzer directement à une broche Arduino produit un son standard, ce qui le rend idéal pour des applications telles que les indicateurs sonores, comme les sons de clavier.
  • D'autre part, lorsqu'il est connecté à une haute tension à travers un relais, il émet un son fort, ce qui le rend approprié pour des signaux d'avertissement.

Le brochage du buzzer piézo-électrique

Le buzzer piézoélectrique a généralement deux broches :

  • La broche négative (-) doit être connectée à la masse (GND, 0 V).
  • La broche positive (+) reçoit le signal de commande du Raspberry Pi (directement ou indirectement via relais).
Broche du buzzer piézoélectrique

Fonctionnement d'un buzzer piézoélectrique

Voir Comment fonctionne le buzzer piézo

Diagramme de câblage

  • Le schéma de câblage entre le Raspberry Pi et le buzzer piézo-électrique
Schéma de câblage du buzzer piézoélectrique Raspberry Pi

Cette image a été créée avec Fritzing. Cliquez pour agrandir l'image.

  • Le schéma de câblage entre le Raspberry Pi et le module de buzzer piézo.
Schéma de câblage du module buzzer piézoélectrique Raspberry Pi

Cette image a été créée avec Fritzing. Cliquez pour agrandir l'image.

Pour simplifier et organiser votre montage de câblage, nous recommandons l'utilisation d'un shield à bornier à vis pour Raspberry Pi. Ce shield assure des connexions plus sûres et mieux gérées, comme illustré ci-dessous :

Shield à bornier à vis pour Raspberry Pi

Code Raspberry Pi

Étapes rapides

  • Assurez-vous d'avoir Raspbian ou tout autre système d'exploitation compatible avec Raspberry Pi installé sur votre Pi.
  • Assurez-vous que votre Raspberry Pi est connecté au même réseau local que votre PC.
  • Assurez-vous que votre Raspberry Pi est connecté à Internet si vous avez besoin d'installer des bibliothèques.
  • Si c'est la première fois que vous utilisez le Raspberry Pi, consultez Installation du logiciel - Raspberry Pi..
  • Connectez votre PC au Raspberry Pi via SSH en utilisant le client SSH intégré sur Linux et macOS ou PuTTY sur Windows. Consultez comment connecter votre PC au Raspberry Pi via SSH.
  • Assurez-vous que la bibliothèque RPi.GPIO est installée. Sinon, installez-la en utilisant la commande suivante :
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Créez un fichier de script Python buzzer.py et ajoutez le code suivant :
# Ce code Raspberry Pi a été développé par newbiely.fr # Ce code Raspberry Pi est mis à disposition du public sans aucune restriction. # Pour des instructions complètes et des schémas de câblage, veuillez visiter: # https://newbiely.fr/tutorials/raspberry-pi/raspberry-pi-piezo-buzzer import RPi.GPIO as GPIO import time # Set the GPIO mode (BCM or BOARD) GPIO.setmode(GPIO.BCM) # Define the GPIO pin number to which the buzzer is connected BUZZER_PIN = 18 # Set up the GPIO pin as an output GPIO.setup(BUZZER_PIN, GPIO.OUT) # Constants for note names and their corresponding frequencies C4 = 261 G3 = 196 A3 = 220 B3 = 247 # Dictionary to map numeric values to note names note_names = { C4: "C4", G3: "G3", A3: "A3", B3: "B3", } # List of notes in the melody melody = [ C4, G3, G3, A3, G3, 0, B3, C4 ] # List of note durations (in milliseconds) note_durations = [ 400, 200, 200, 400, 400, 400, 400, 400 ] # Pause duration between notes (in milliseconds) pause_duration = 300 def play_tone(pin, frequency, duration): # Calculate the period based on the frequency period = 1.0 / frequency # Calculate the time for half of the period half_period = period / 2.0 # Calculate the number of cycles for the given duration cycles = int(duration / period) for _ in range(cycles): # Set the GPIO pin to HIGH GPIO.output(pin, GPIO.HIGH) # Wait for half of the period time.sleep(half_period) # Set the GPIO pin to LOW GPIO.output(pin, GPIO.LOW) # Wait for the other half of the period time.sleep(half_period) try: while True: # Infinite loop # Iterate over the notes of the melody for i in range(len(melody)): # To calculate the note duration, take the value from the list and divide it by 1,000 (convert to seconds) note_duration = note_durations[i] / 1000.0 note_freq = melody[i] note_name = note_names.get(note_freq, "Pause") print(f"Playing {note_name} (Frequency: {note_freq} Hz) for {note_duration} seconds") # Play the tone play_tone(BUZZER_PIN, note_freq, note_duration) # Add a brief pause between notes (optional) time.sleep(pause_duration / 1000.0) # Stop the tone playing (optional) GPIO.output(BUZZER_PIN, GPIO.LOW) # Allow the user to stop the buzzer by pressing Ctrl+C except KeyboardInterrupt: GPIO.output(BUZZER_PIN, GPIO.LOW) GPIO.cleanup()
  • Enregistrez le fichier et exécutez le script Python en exécutant la commande suivante dans le terminal :
python3 buzzer.py
  • Écoutez la mélodie d'une chanson émise par le buzzer piézo.

Le script fonctionne en boucle infinie jusqu'à ce que vous appuyiez sur Ctrl + C dans le terminal.

Modification du code Raspberry Pi

Maintenant, nous allons modifier le code pour jouer la chanson "Jingle Bells".

  • Créez un fichier de script Python buzzer_Jingle_Bells.py et ajoutez le code suivant :
# Ce code Raspberry Pi a été développé par newbiely.fr # Ce code Raspberry Pi est mis à disposition du public sans aucune restriction. # Pour des instructions complètes et des schémas de câblage, veuillez visiter: # https://newbiely.fr/tutorials/raspberry-pi/raspberry-pi-piezo-buzzer import RPi.GPIO as GPIO import time # Set the GPIO mode (BCM or BOARD) GPIO.setmode(GPIO.BCM) # Define the GPIO pin number to which the buzzer is connected BUZZER_PIN = 18 # Set up the GPIO pin as an output GPIO.setup(BUZZER_PIN, GPIO.OUT) # Constants for note names and their corresponding frequencies C4 = 261 D4 = 293 E4 = 329 F4 = 349 G4 = 392 A4 = 440 B4 = 493 # Dictionary to map numeric values to note names note_names = { C4: "C4", D4: "D4", E4: "E4", F4: "F4", G4: "G4", A4: "A4", B4: "B4", } # List of notes in the "Jingle Bells" melody melody = [ E4, E4, E4, E4, E4, E4, E4, G4, C4, D4, E4, F4, F4, F4, F4, F4, E4, E4, E4, E4, E4, D4, D4, E4, D4, G4 ] # List of note durations (in milliseconds) note_durations = [ 200, 200, 400, 200, 200, 400, 200, 200, 200, 200, 200, 200, 200, 400, 200, 200, 200, 200, 200, 200, 200, 200, 200, 400, 200, 200 ] # Pause duration between notes (in milliseconds) pause_duration = 300 def play_tone(pin, frequency, duration): # Calculate the period based on the frequency period = 1.0 / frequency # Calculate the time for half of the period half_period = period / 2.0 # Calculate the number of cycles for the given duration cycles = int(duration / period) for _ in range(cycles): # Set the GPIO pin to HIGH GPIO.output(pin, GPIO.HIGH) # Wait for half of the period time.sleep(half_period) # Set the GPIO pin to LOW GPIO.output(pin, GPIO.LOW) # Wait for the other half of the period time.sleep(half_period) try: while True: # Infinite loop # Iterate over the notes of the melody for i in range(len(melody)): # To calculate the note duration, take the value from the list and divide it by 1,000 (convert to seconds) note_duration = note_durations[i] / 1000.0 note_freq = melody[i] note_name = note_names.get(note_freq, "Pause") print(f"Playing {note_name} (Frequency: {note_freq} Hz) for {note_duration} seconds") # Play the tone play_tone(BUZZER_PIN, note_freq, note_duration) # Add a brief pause between notes (optional) time.sleep(pause_duration / 1000.0) # Stop the tone playing (optional) GPIO.output(BUZZER_PIN, GPIO.LOW) # Allow the user to stop the buzzer by pressing Ctrl+C except KeyboardInterrupt: GPIO.output(BUZZER_PIN, GPIO.LOW) GPIO.cleanup()
  • Enregistrez le fichier et exécutez le script Python en lançant la commande suivante dans le terminal :
python3 buzzer_Jingle_Bells.py
  • Vous pouvez comparer ce code avec le code précédent pour voir les différences.

Avec cette modification, le code jouera désormais la mélodie de "Jingle Bells" en utilisant le buzzer piézoélectrique connecté au Raspberry Pi. Profitez de l'air festif !

Vidéo

Défiez-vous

  • Utilisez un buzzer piézoélectrique pour jouer votre chanson préférée.
  • Utilisez un capteur de mouvement Raspberry Pi pour déclencher automatiquement une alarme lorsque quelqu'un s'approche de vos objets de valeur. Consultez Raspberry Pi - Capteur de mouvement. pour plus d'informations.

※ NOS MESSAGES

  • N'hésitez pas à partager le lien de ce tutoriel. Cependant, veuillez ne pas utiliser notre contenu sur d'autres sites web. Nous avons investi beaucoup d'efforts et de temps pour créer ce contenu, veuillez respecter notre travail !