Raspberry Pi - Bouton - Buzzer Piézo

Ce tutoriel vous explique comment utiliser un Raspberry Pi et un bouton pour contrôler un buzzer piézoélectrique. Les actions suivantes seront discutées en détail :

Préparation du matériel

1×Raspberry Pi 5
1×Bouton avec capuchon pour plaque d'essai
1×Kit bouton pour plaque d'essai
1×Bouton poussoir pour montage sur panneau
1×Module bouton poussoir
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 et du bouton

Si vous n'êtes pas familier avec le buzzer piézo et le bouton (y compris le brochage, leur fonctionnement, et comment les programmer), les tutoriels suivants peuvent vous aider :

Diagramme de câblage

Schéma de câblage d'un bouton et d'un buzzer piézo pour 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 - Son Simple

Dans cette partie, nous allons apprendre à utiliser un buzzer piézoélectrique pour émettre un son simple lorsque le bouton est pressé en utilisant le 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 devez installer des bibliothèques.
  • Si c'est la première fois que vous utilisez 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 vous avez la bibliothèque RPi.GPIO 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 button_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-button-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 # Define the GPIO pin number to which the button is connected BUTTON_PIN = 16 # Set up the GPIO pins GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up resistor GPIO.setup(BUZZER_PIN, GPIO.OUT) # Output try: while True: button_state = GPIO.input(BUTTON_PIN) if button_state == GPIO.LOW: print("The button is being pressed") GPIO.output(BUZZER_PIN, GPIO.HIGH) # Turn the buzzer on else: print("The button is unpressed") GPIO.output(BUZZER_PIN, GPIO.LOW) # Turn the buzzer off # Add a slight delay to debounce the button (optional) time.sleep(0.1) # Allow the user to stop the buzzer by pressing Ctrl+C except KeyboardInterrupt: GPIO.output(BUZZER_PIN, GPIO.LOW) # Turn off the buzzer GPIO.cleanup()
  • Enregistrez le fichier et exécutez le script Python en exécutant la commande suivante dans le terminal :
python3 button_buzzer.py
  • Maintenez le bouton enfoncé pendant plusieurs secondes.
  • Écoutez le son du buzzer piézo.

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

Explication du Code

Consultez l'explication ligne par ligne contenue dans les commentaires du code source !

Raspberry Pi joue la mélodie de la chanson

Dans cette partie, nous ferons en sorte que le Raspberry Pi déclenche le buzzer piézoélectrique pour jouer la chanson "Jingle Bells" lorsqu'un bouton est pressé.

Étapes rapides

  • Créez un fichier de script Python button_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-button-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 # Define the GPIO pin number to which the button is connected BUTTON_PIN = 16 # Set up the GPIO pins GPIO.setup(BUZZER_PIN, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # 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) def play_jingle_bells(): for i in range(len(melody)): 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_tone(BUZZER_PIN, note_freq, note_duration) time.sleep(pause_duration / 1000.0) GPIO.output(BUZZER_PIN, GPIO.LOW) try: while True: button_state = GPIO.input(BUTTON_PIN) if button_state == GPIO.LOW: play_jingle_bells() # 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 button_buzzer_Jingle_Bells.py
  • Appuyez sur le bouton
  • Ensuite, écoutez la mélodie du buzzer piézo.

Explication du code

Consultez l'explication ligne par ligne contenue dans les commentaires du code source !

Vidéo

※ 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 !