Arduino 語言提供的 tone()
函式可以用於使用被動蜂鳴器播放音符。
結合不同的 tone()
調用,我們可以播放曲子。
以下是使用方式:
tone(<PIN>, <FREQUENCY>)
例如,在連接到引腳 8 的蜂鳴器上播放 C7 音符:
#define NOTE\_C7 2093
tone(8, NOTE\_C7)
頻率以赫茲 (hz) 表示
可以調用 noTone(<PIN>)
函式停止播放:
tone(8, NOTE\_C7)
delay(100)
noTone(8)
第三個參數可以設置音符的持續時間,這樣就不需要調用 noTone()
函式:
tone(8, NOTE\_C7, 100)
我從 Arduino 官方的 toneMelody
範例 中獲得了其他音符的頻率。我在這裡將它們複製供參考:
#define NOTE\_B0 31
#define NOTE\_C1 33
#define NOTE\_CS1 35
#define NOTE\_D1 37
#define NOTE\_DS1 39
#define NOTE\_E1 41
#define NOTE\_F1 44
#define NOTE\_FS1 46
#define NOTE\_G1 49
#define NOTE\_GS1 52
#define NOTE\_A1 55
#define NOTE\_AS1 58
#define NOTE\_B1 62
#define NOTE\_C2 65
#define NOTE\_CS2 69
#define NOTE\_D2 73
#define NOTE\_DS2 78
#define NOTE\_E2 82
#define NOTE\_F2 87
#define NOTE\_FS2 93
#define NOTE\_G2 98
#define NOTE\_GS2 104
#define NOTE\_A2 110
#define NOTE\_AS2 117
#define NOTE\_B2 123
#define NOTE\_C3 131
#define NOTE\_CS3 139
#define NOTE\_D3 147
#define NOTE\_DS3 156
#define NOTE\_E3 165
#define NOTE\_F3 175
#define NOTE\_FS3 185
#define NOTE\_G3 196
#define NOTE\_GS3 208
#define NOTE\_A3 220
#define NOTE\_AS3 233
#define NOTE\_B3 247
#define NOTE\_C4 262
#define NOTE\_CS4 277
#define NOTE\_D4 294
#define NOTE\_DS4 311
#define NOTE\_E4 330
#define NOTE\_F4 349
#define NOTE\_FS4 370
#define NOTE\_G4 392
#define NOTE\_GS4 415
#define NOTE\_A4 440
#define NOTE\_AS4 466
#define NOTE\_B4 494
#define NOTE\_C5 523
#define NOTE\_CS5 554
#define NOTE\_D5 587
#define NOTE\_DS5 622
#define NOTE\_E5 659
#define NOTE\_F5 698
#define NOTE\_FS5 740
#define NOTE\_G5 784
#define NOTE\_GS5 831
#define NOTE\_A5 880
#define NOTE\_AS5 932
#define NOTE\_B5 988
#define NOTE\_C6 1047
#define NOTE\_CS6 1109
#define NOTE\_D6 1175
#define NOTE\_DS6 1245
#define NOTE\_E6 1319
#define NOTE\_F6 1397
#define NOTE\_FS6 1480
#define NOTE\_G6 1568
#define NOTE\_GS6 1661
#define NOTE\_A6 1760
#define NOTE\_AS6 1865
#define NOTE\_B6 1976
#define NOTE\_C7 2093
#define NOTE\_CS7 2217
#define NOTE\_D7 2349
#define NOTE\_DS7 2489
#define NOTE\_E7 2637
#define NOTE\_F7 2794
#define NOTE\_FS7 2960
#define NOTE\_G7 3136
#define NOTE\_GS7 3322
#define NOTE\_A7 3520
#define NOTE\_AS7 3729
#define NOTE\_B7 3951
#define NOTE\_C8 4186
#define NOTE\_CS8 4435
#define NOTE\_D8 4699
#define NOTE\_DS8 4978