麥克風感應器和旋律

麥克風感應器

MicroPython 程式碼範例 運行在 Raspberry Pi Pico 2 W 微控制器上 在麵包板上,​​連接麥克風聲音感測器模組、被動壓電蜂鳴器和OLED顯示模組(SSD1306)。 重播蜂鳴器上麥克風測量的聲音頻率,並將其顯示在螢幕上。

麥克風聲音感測器利用內建麥克風和板載處理電路,將環境聲波轉換為電訊號。. 聲波在空氣中傳播,並撞擊模組麥克風內部的微型柔性振膜。. 隔膜的波動會產生與聲音頻率和音量相符的電訊號。. 執行此腳本,同時在另一台裝置上執行 melody.py。. 將兩個裝置靠近,並將麥克風直接放在播放旋律的裝置的蜂鳴器上方。. 如果房間不太吵鬧,它應該至少可以拿起一些音符。.

暗示

若要在其他裝置上快速執行 melody.py,而無需上傳新程式碼,請使用「入門指南」部分中所述的替代方法。.

在 Thonny 中建立一個名為 microphone_sensor.py 的新檔案。. 將以下程式碼複製並貼上到您建立的文件中。.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
print("\nMicrophone Sensor")

# DESCRIPTION

# A microphone sound sensor converts environmental sound waves into electrical 
# signals using a built-in microphone and an onboard processing circuit. Sound waves 
# move through the air and hit a tiny flexible diaphragm inside the module's microphone.
# The fluctuations in the diaphragm create electrical signals that match the sound 
# frequency and volume. Run this script, and simultaneously run melody.py on a different 
# device. Bring the devices close to each other and place the microphone directly on top of
# the buzzer of the device playing the melody. If the room is not very noisy, it should pick
# up at least some of the notes.

# CONNECTIONS REQUIRED

# Connect Microphone Sensor (KY-037) module 
# (it includes a cylindrical mic with black circular pad on top)
#   Pins: GND => GND, VCC => VCC, S => GP28

from time import sleep
from machine import Pin, ADC
from oled import OLED
from buzzer import Buzzer
from value_filter import ValueFilter
from helper import interpolate

mic_sensor = ADC(Pin(28))
value_filter = ValueFilter(filter="SMA", window_size=5)
oled = OLED(scl_pin=15, sda_pin=14)
buzzer = Buzzer(pwm_pin=16)

sensor_min = 8000
sensor_max = 13000
frequency = 0

try:
    while True:
        # Use Simple Moving Average filter to smooth out readings
        sensor_value = value_filter.update(mic_sensor.read_u16())

        # Convert sensor_value to frequency when reading is greater than sensor_min
        # and buzzer is not playing (frequency == 0).
        # If buzzer is already playing, don't change frequency.
        # If sensor_value drops below 75% of sensor_min, reset frequency to stop buzzer
        if sensor_value < sensor_min * 0.75: frequency = 0
        elif sensor_value >= sensor_min and frequency == 0:
            frequency = interpolate(sensor_value, sensor_min, sensor_max, 200, 600)

        oled.print(f"Raw: {sensor_value:.0f}", f"Freq: {frequency}")
        buzzer.play_tone(frequency, 0)
        sleep(0.02)

except KeyboardInterrupt:
    print("\nInterrupted by user!")

finally:
    oled.reset()
    buzzer.reset()

要測試 melody.py 在不同裝置上運行的情況,請在連接到第二個裝置的電腦上執行上述旋律實驗中的 melody.py 檔案。.


回到頂部

讓教師和學生更容易參與動手發明創造.
© 2026 Inventor Pi, Inc.
Inventor Pi, Inc.是一家註冊的 501(c)(3) 非營利組織