PWM - 通過蜂鳴器播放音樂

材料準備

  • AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1

  • 蜂鸣器 x 1

範例説明

聲音的組成包括音量、音調與音色。音量為聲波的振幅,音調為聲波的頻率,音色則是由聲波的波形決定。

這個範例裡我們使用PWM控制蜂鳴器發出想要的音調。 PWM輸出的是方波,當我們想要發出中央C(C4)的聲音時,C4的頻率是262Hz,每個波的長度是 1/262 = 3.8ms,所以波形如下:

../../../../_images/image158.png

所以我們只要讓PWM送出不同的頻率,就可以讓蜂鳴器發出音樂

接著我們將蜂鳴器接上要發出訊號的PWM pin腳:

AMB21/AMB22 的接線圖:

../../../../_images/image255.png

AMB23 的接線圖

../../../../_images/image337.png

BW16 的接線圖

../../../../_images/image3-16.png

BW16-TypeC Wiring Diagram:

../../../../_images/image3-23.png

Open the example code in “Examples” “AmebaAnalog” “TonePlayMelody” Compile and upload to Ameba, press the reset button. Then you can hear the buzzer playing music.

程式碼説明

Ameba implement the tone() and noTone() API of Arduino: https://www.arduino.cc/en/Reference/Tone https://www.arduino.cc/en/Reference/NoTone

程式碼裡我們宣告melody的陣列, 裡面擺要發出的音調, 另外宣告noteDurations的陣列,裡面放每個音調的長度, 4代表4分音符, 8代表8分音符,4分音符的長度是3000ms/ 4 = 750ms, 另外加上30%的停頓時間。