Raspberry Pi Piezo Buzzer

Hướng dẫn này sẽ chỉ bạn cách sử dụng Raspberry Pi để điều khiển piezo buzzer. Cụ thể, chúng ta sẽ học:

Phần Cứng Cần Thiết

1×Raspberry Pi 5
1×3-24V Active Piezo Buzzer
1×Active Piezo Buzzer Module
1×Passive Piezo Buzzer Module
1×breadboard (bo mạch thí nghiệm)
1×dây jumper (dây nối)
1×(Khuyến nghị) Screw Terminal Block Shield for Raspberry Pi
1×(Khuyến nghị) Raspberry Pi Prototyping Base Plate & Breadboard Kit
1×(Khuyến nghị) HDMI Touch Screen Monitor for Raspberry Pi

Or you can buy the following kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)

Về Piezo Buzzer

Piezo Buzzer được sử dụng để tạo âm thanh, tiếng beep, hoặc thậm chí là giai điệu của một bài hát.

Hiện có trên thị trường là 3V-24V active buzzer có hai mục đích sử dụng: hoạt động vừa như một active buzzer 3-5V và một buzzer điện áp cao (từ 12V trở lên).

  • Kết nối buzzer này trực tiếp với chân Raspberry Pi sẽ tạo ra âm thanh tiêu chuẩn, rất lý tưởng cho các ứng dụng như chỉ báo âm thanh, như tiếng bàn phím.
  • Mặt khác, khi kết nối với điện áp cao thông qua relay, nó phát ra âm thanh lớn, phù hợp cho tín hiệu cảnh báo.

Sơ Đồ Chân Piezo Buzzer

Piezo Buzzer thường có hai chân:

  • Chân Âm (-) nên được kết nối với GND (0V)
  • Chân Dương (+) nhận tín hiệu điều khiển từ Raspberry Pi (trực tiếp hoặc gián tiếp qua relay)
còi piezo sơ đồ chân

Cách Hoạt Động Của Piezo Buzzer

Xem Cách hoạt động của Piezo Buzzer

Sơ Đồ Kết Nối

  • Sơ đồ kết nối giữa Raspberry Pi và Piezo Buzzer
Raspberry Pi còi piezo sơ đồ đấu dây

This image is created using Fritzing. Click to enlarge image

  • Sơ đồ kết nối giữa Raspberry Pi và Piezo Buzzer module
Raspberry Pi còi piezo module sơ đồ đấu dây

This image is created using Fritzing. Click to enlarge image

Code Raspberry Pi

Các Bước Nhanh

  • Đảm bảo bạn đã cài đặt Raspbian hoặc bất kỳ hệ điều hành nào khác tương thích với Raspberry Pi trên Pi của bạn.
  • Đảm bảo Raspberry Pi của bạn được kết nối với cùng mạng cục bộ như PC của bạn.
  • Đảm bảo Raspberry Pi của bạn được kết nối internet nếu bạn cần cài đặt một số thư viện.
  • Nếu đây là lần đầu tiên bạn sử dụng Raspberry Pi, xem Raspberry Pi - Cài Đặt Phần Mềm
  • Kết nối PC của bạn với Raspberry Pi thông qua SSH sử dụng SSH client có sẵn trên Linux và macOS hoặc PuTTY trên Windows. Xem cách kết nối PC với Raspberry Pi qua SSH.
  • Đảm bảo bạn đã cài đặt thư viện RPi.GPIO. Nếu chưa, hãy cài đặt bằng lệnh sau:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Tạo file script Python buzzer.py và thêm code sau:
# Mã Raspberry Pi này được phát triển bởi newbiely.vn # Mã Raspberry Pi này được cung cấp để sử dụng công khai, không có ràng buộc. # Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: # https://newbiely.vn/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()
  • Lưu file và chạy script Python bằng cách thực hiện lệnh sau trong terminal:
python3 buzzer.py
  • Lắng nghe giai điệu của bài hát phát ra từ piezo buzzer.

Script chạy trong vòng lặp vô hạn liên tục cho đến khi bạn nhấn Ctrl + C trong terminal.

Chỉnh Sửa Code Raspberry Pi

Bây giờ, chúng ta sẽ thay đổi code để phát bài hát "Jingle Bells".

  • Tạo file script Python buzzer_Jingle_Bells.py và thêm code sau:
# Mã Raspberry Pi này được phát triển bởi newbiely.vn # Mã Raspberry Pi này được cung cấp để sử dụng công khai, không có ràng buộc. # Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: # https://newbiely.vn/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()
  • Lưu file và chạy script Python bằng cách thực hiện lệnh sau trong terminal:
python3 buzzer_Jingle_Bells.py
  • Bạn có thể so sánh code này với code trước đó để thấy sự khác biệt

Với thay đổi này, code bây giờ sẽ phát giai điệu "Jingle Bells" sử dụng piezo buzzer được kết nối với Raspberry Pi. Hãy thưởng thức giai điệu lễ hội!

Video Tutorial

Việc sản xuất video tốn rất nhiều thời gian. Nếu video hướng dẫn hữu ích cho việc học của bạn, hãy đăng ký kênh YouTube để ủng hộ. Nếu nhu cầu đủ cao, chúng tôi sẽ cố gắng làm thêm nhiều video.

Thử Thách Bản Thân

  • Sử dụng Piezo Buzzer để phát bài hát yêu thích của bạn.
  • Sử dụng Raspberry Pi Motion Sensor để tự động phát báo động khi có ai đó gần đồ vật có giá trị của bạn. Tham khảo Raspberry Pi - Cảm Biến Chuyển Động để biết thêm thông tin.