调声函数
tone()主要用于连接蜂鸣器或者扬声器发声场合,实质是输出一个频率可调方波,来驱动蜂鸣器或者扬声器发声。
tone(pin,frequency,duration)
pin 需要输出方波的引脚。
frequency 输出的频率。
duration 频率持续的时间,单位为毫秒。如果没有该参数,将会持续发出设定的音调。
同一时间tone()函数只能作用一个引脚如果有多个引脚需要用到,则需要停止之前的引脚。
noTone()停止指定引脚的方波输出。
材料准备
无源蜂鸣器、arduino、100欧电阻、导线
线路图

由于没有100欧电阻,尝试用220欧电阻看到底合不合适。
代码部分
/*
Melody
Plays a melody
circuit:
- 8 ohm speaker on digital pin 8
created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Tone
*/
#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(8, 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(8);
}
}
void loop() {
// no need to repeat the melody.
}
自己写的注释
#include "pitches.h"
int melody[]={
NOTE_C4,NOTE_G3,NOTE_G3,NOTE_A3,NOTE_G3,NOTE_B3,NOTE_C4};
//定义一个字符串,反正是个容器装下一些定义好的音符信息。
int noteDurations[]={
4,8,8,4,4,4,4,4};
//定义一个数组,装有单个音符持续的时间,音乐名词叫做4分音符8分音符,不了解
void setup() {
for (int thisNote =0; thisNote<8; thisNote++)
//进行遍历,因为只有8个音符,将这几个音符遍历一遍就可以了
{
int noteDuration = 1000/noteDurations[thisNote];
//音符的换算1000/4>1000/8,难道4分音符持续时间比8分音符更长?
tone(8,melody[thisNote],noteDuration);//8号引脚,输出频率,持续时长
int pauseBetweenNotes = noteDuration*1.30;
delay(pauseBetweenNotes);//大概比较长的英文单词让中国人感到编程很难,英文释义可能在外国人眼中比较直观吧。
noTone(8);//停止方波输出引脚
}
}
void loop() {
// put your main code here, to run repeatedly:不需要写
}
代码为arduino自带的示例,感觉挺单调的声音,很机械。

自己制作pitches.h文件步骤

点击这个小三角,有一个新建标签,点击进入

这里输入新文件的名字,点击‘好’就可以了。将实例中的内容复制复制过来就可以了。
这样就能使用#include"pitches.h"了。

网友评论