Home » openCR入门教程 » OpenCR入门教程-开发示例-蜂鸣器

OpenCR入门教程-开发示例-蜂鸣器

说明

  • 本教程介绍OpenCR板上的内置蜂鸣器测试示例

代码

  • OpenCR有内置的BUZZER,声音取决于频率。内置的BUZZER也映射到arduino引脚号,并且arduino引脚号如下

  • 同时移植了Arduino的Tone功能,因此可以通过使用BUZZER使用该功能

  • 其根据pitches.h标头中定义的音阶输出旋律

//The following code is a change from OpenCR's BUZZER to only the PIN number in the example provided in the Arduino IDE.
#define BDPIN_BUZZER            31

#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; thisNote++) {

    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(BDPIN_BUZZER, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(BDPIN_BUZZER);
  }
}

演示视频

纠错,疑问,交流: 请进入讨论区点击加入Q群

获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


标签: none