Raspberry Pi Cảm Biến Siêu Âm Piezo Buzzer

Hướng dẫn này sẽ chỉ bạn cách sử dụng Raspberry Pi và cảm biến siêu âm để điều khiển piezo buzzer. Cụ thể:

Linh Kiện Cần Thiết

1×Raspberry Pi 5
1×Cảm Biến Siêu Âm
1×Active Piezo Buzzer 3-24V
1×Module Active Piezo Buzzer
1×Module Passive Piezo Buzzer
1×breadboard (Bo mạch thí nghiệm)
1×Dây Jumper
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 và Cảm Biến Siêu Âm

Nếu bạn chưa quen thuộc với piezo buzzer và cảm biến siêu âm (bao gồm sơ đồ chân, cách hoạt động và cách lập trình), các hướng dẫn sau có thể cung cấp thêm thông tin cho bạn:

Sơ Đồ Kết Nối

sơ đồ kết nối Raspberry Pi cảm biến siêu Âm còi piezo

This image is created using Fritzing. Click to enlarge image

Code Raspberry Pi - Âm Thanh Đơn Giản

Trong phần này, chúng ta sẽ lập trình Raspberry Pi để điều khiển piezo buzzer phát ra âm thanh đơn giản bất cứ khi nào khoảng cách đo được bởi cảm biến siêu âm thấp hơn ngưỡng đặt trước.

Các Bước Thực Hiện

  • Đảm bảo bạn đã cài đặt Raspbian hoặc hệ điều hành tương thích khác với Raspberry Pi.
  • Đảm bảo Raspberry Pi của bạn đã kết nối với cùng mạng cục bộ với máy tính của bạn.
  • Đảm bảo Raspberry Pi của bạn đã kết nối internet nếu cần cài đặt các thư viện.
  • Nếu đây là lần đầu tiên bạn sử dụng Raspberry Pi, hãy xem Raspberry Pi - Cài Đặt Phần Mềm
  • Kết nối máy tính của bạn với Raspberry Pi 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 máy tính 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 ultrasonic_sensor_buzzer.py và thêm đoạn 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-ultrasonic-sensor-piezo-buzzer import RPi.GPIO as GPIO import time # GPIO pin numbers for the ultrasonic sensor TRIG_PIN = 14 ECHO_PIN = 15 # GPIO pin number for the piezo buzzer BUZZER_PIN = 16 # Threshold distance in centimeters THRESHOLD_DISTANCE_CM = 20 def get_distance(): GPIO.output(TRIG_PIN, GPIO.HIGH) time.sleep(0.00001) GPIO.output(TRIG_PIN, GPIO.LOW) while GPIO.input(ECHO_PIN) == 0: pulse_start = time.time() while GPIO.input(ECHO_PIN) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start speed_of_sound = 34300 # Speed of sound in cm/s distance = (pulse_duration * speed_of_sound) / 2 return distance GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) GPIO.setup(BUZZER_PIN, GPIO.OUT) GPIO.output(TRIG_PIN, GPIO.LOW) GPIO.output(BUZZER_PIN, GPIO.LOW) try: while True: distance = get_distance() print(f"Distance: {distance:.2f} cm") if distance < THRESHOLD_DISTANCE_CM: GPIO.output(BUZZER_PIN, GPIO.HIGH) # Turn the buzzer on else: GPIO.output(BUZZER_PIN, GPIO.LOW) # Turn the buzzer off except KeyboardInterrupt: GPIO.cleanup()
  • Lưu file và chạy script Python bằng cách thực thi lệnh sau trong terminal:
python3 ultrasonic_sensor_buzzer.py
  • Vẫy tay trước mặt cảm biến.
  • Lắng nghe âm thanh 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.

Giải Thích Code

Hãy xem giải thích từng dòng code trong phần comment của source code!

Raspberry Pi Phát Giai Điệu Bài Hát

Trong phần này, chúng ta sẽ lập trình Raspberry Pi để kích hoạt piezo buzzer phát bài hát "Jingle Bells" khi khoảng cách nhỏ hơn ngưỡng đặt trước.

Các Bước Thực Hiện

  • Tạo file script Python ultrasonic_sensor_buzzer_Jingle_Bells.py và thêm đoạn 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-ultrasonic-sensor-piezo-buzzer import RPi.GPIO as GPIO import time # GPIO pin numbers for the ultrasonic sensor TRIG_PIN = 14 ECHO_PIN = 15 # GPIO pin number for the piezo buzzer BUZZER_PIN = 16 # Threshold distance in centimeters THRESHOLD_DISTANCE_CM = 20 # 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) def get_distance(): GPIO.output(TRIG_PIN, GPIO.HIGH) time.sleep(0.00001) GPIO.output(TRIG_PIN, GPIO.LOW) while GPIO.input(ECHO_PIN) == 0: pulse_start = time.time() while GPIO.input(ECHO_PIN) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start speed_of_sound = 34300 # Speed of sound in cm/s distance = (pulse_duration * speed_of_sound) / 2 return distance GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) GPIO.setup(BUZZER_PIN, GPIO.OUT) GPIO.output(TRIG_PIN, GPIO.LOW) GPIO.output(BUZZER_PIN, GPIO.LOW) try: while True: distance = get_distance() print(f"Distance: {distance:.2f} cm") if distance < THRESHOLD_DISTANCE_CM: play_jingle_bells() except KeyboardInterrupt: GPIO.cleanup()
  • Lưu file và chạy script Python bằng cách thực thi lệnh sau trong terminal:
python3 ultrasonic_sensor_buzzer_Jingle_Bells.py
  • Di chuyển tay trước mặt cảm biến.
  • Nghe giai điệu được phát bởi piezo buzzer.

Giải Thích Code

Hãy xem giải thích từng dòng code trong phần comment của source code!

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.