最近在学用arduino控制传感器,顺带着就玩儿了一下蜂鸣器。按照简谱写出了《大鱼》对应的代码。
其他音乐也可以按照这个思路编写出相对应的控制程序。
大概思路如下:
定义不同音所对应的频率,按照简谱写出音符对应的常量放在一个数组内,写控制节奏的数组
setup函数,设置蜂鸣器连接的引脚,计算乐谱的长度
loop函数,按顺序发声、停顿,整首曲子结束后停顿2s,再从头播放
硬件接线:
蜂鸣器-arduino
正-D6
负-GND
#define NTC0 -1
#define NTC1 262
#define NTC2 294
#define NTC3 330
#define NTC4 350
#define NTC5 393
#define NTC6 441
#define NTC7 495
#define NTCL5 196
#define NTCL6 221
#define NTCL7 248
#define NTCH1 525
//音符
int tune[]=
{
NTC3,NTC2,NTC3,NTC6,NTC3,NTC2,NTC3,NTC7,
NTC3,NTC2,NTC3,NTCH1,NTC7,NTC5,
NTC3,NTC2,NTC3,NTC6,NTC3,NTC2,NTC3,NTC7,
NTC5,NTC2,NTCL7,
NTC3,NTC2,NTC3,NTC6,NTC3,NTC2,NTC3,NTC7,
NTC3,NTC2,NTC3,NTCH1,NTC7,NTC5,
NTC2,NTC3,NTCL6,NTC2,NTC3,NTCL6,NTCL5,
NTCL6,NTC1,NTCL7,
NTCL6,NTC1,NTC1,NTC2,NTC2,NTC3,NTC3,NTC5,NTC6,
NTC5,NTC3,NTC2,
NTCL6,NTC1,NTC1,NTC2,NTC2,NTC3,NTC3,NTCL6,NTCL5,
NTCL6,NTC1,NTC1,NTC2,NTC2,NTC3,NTC3,NTC5,NTC6,
NTC5,NTC3,NTC2,
NTC2,NTC3,NTCL6,NTC2,NTC3,NTCL6,NTCL5,NTCL6,
NTCL6,NTC1,NTC2,NTC1,NTCL6,
NTCL6,NTC1,NTC2,NTC1,NTC3,
NTC3,NTC5,NTC6,NTC6,NTC5,NTC3,NTC2,NTC1,NTC2,NTC3,
NTCL6,NTC1,NTC2,NTC1,NTCL6,
NTCL6,NTC1,NTC2,NTC1,NTC3,
NTC2,NTC3,NTCL6,NTC2,NTC3,NTCL6,NTCL5,NTCL6,
NTC3,NTC5,NTCH1,NTC7,NTC3,
NTC3,NTC2,NTC1,NTC1,NTC2,NTC3,
NTC3,NTC2,NTC1,NTC6,NTCH1,NTC7,NTC6,NTC5,NTC2,NTC3,
NTC3,NTC5,NTCH1,NTC7,NTC3,
NTC3,NTC2,NTC1,NTC1,NTC2,NTC3,
NTC2,NTC3,NTCL6,NTC2,NTC3,NTCL6,NTCL5,NTCL6,
};
//节拍
int durt[]=
{
250,250,250,250,250,250,250,250,
250,250,250,250,500,500,
250,250,250,250,250,250,250,250,
500,500,1000,
250,250,250,250,250,250,250,250,
250,250,250,250,500,500,
250,250,500,250,250,250,250,500,500,1000,
250,250,250,250,250,250,250,125,125,
750,250,1000,
250,250,250,250,250,250,500,500,1500,
250,250,250,250,250,250,250,125,125,
750,250,1000,
250,250,500,250,250,250,250,1500,
250,250,750,250,500,250,250,
750,250,500,250,250,500,250,250,250,250,500,500,1000,
250,250,875,125,500,250,250,500,500,1000,
250,250,500,250,250,250,250,1500,
250,250,750,250,500,250,250,
500,250,250,500,250,250,500,250,250,250,250,250,250,1500,
250,250,750,250,500,250,250,
500,250,250,1000,250,250,500,250,250,250,250,2000,
};
int length;
int tonepin=6;
void setup()
{
pinMode(tonepin,OUTPUT);
length=sizeof(tune)/sizeof(tune[0]);
}
void loop()
{
for(int x=0;x<length;x++)
{
tone(tonepin,tune[x]);
delay(durt[x]);
noTone(tonepin);
}
delay(2000);
}