蜂鸣器播放简单歌曲

来自Microduino Wikipedia
1196357542@qq.com讨论 | 贡献2018年5月31日 (四) 08:36的版本
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航搜索

Sensor-Buzzer库-播放简单歌曲


在下面的示例中,使用Core核心控制蜂鸣器播放简单的歌曲。

所需硬件


电路搭建

将Battery、Core、MCookie_Hub堆叠在一起,将蜂鸣器插在D6引脚。

代码

#define buzzer_pin 6 //定义蜂鸣器驱动引脚

int song[] = {
  262, 262, 294, 262, 349, 330,
  262, 262, 294, 262, 392, 349,
  262, 262, 523, 440, 349, 330, 294,
  494, 494, 440, 349, 392, 349
};

int noteDurations[] = {
  4, 4, 2, 2, 2, 1,
  4, 4, 2, 2, 2, 1,
  4, 4, 2, 2, 2, 2, 2,
  4, 4, 2, 2, 2, 1
};

void setup() {
  pinMode(buzzer_pin, OUTPUT);
}

void loop() {
  song_play();
}

void song_play()
{
  for (int thisNote = 0; thisNote < 25; thisNote++)
  {
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(buzzer_pin, song[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.20;
    delay(pauseBetweenNotes);
    noTone(buzzer_pin);
  }
}

“song_play()”为播放音乐函数,“song[]”里面存放音调(频率),“noteDurations[]”为节拍。 音乐由tone()函数控制,改动该函数即可改变音乐旋律,代码有两种形式分别为:tone(pin, frequency, duration)或tone(pin, frequency) 第一个函数中,pin代表连接扬声器的管脚,frequency代表发声频率,duration代表持续的时间,单位是毫秒。 如果用第二个函数,则还需另外的noTone()函数来控制音乐的停止noTone(pin)。


返回Sensor-Buzzer界面