今天晚上波波为大家分享Arduino无源蜂鸣器实验,通过程序让无源蜂鸣器有规则的播放乐曲。其实这个实验比较简单,在网上也能看到很多相关教程,在这里波波仅记录下这次实验的详细步骤以供学习。
实验材料:
1、Arduino uno R3
2、V5 扩展板一块(不是必须的)
3、无源蜂鸣器1个。
实验步骤:
1、连线:
把无源蜂鸣器上面的VCC、GND、I/O分别接在开发板或扩展板的+5V 、GND、D8上面。
2、写入以下程序:
- #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 NTCL1 131
- #define NTCL2 147
- #define NTCL3 165
- #define NTCL4 175
- #define NTCL5 196
- #define NTCL6 221
- #define NTCL7 248
- #define NTCH1 525
- #define NTCH2 589
- #define NTCH3 661
- #define NTCH4 700
- #define NTCH5 786
- #define NTCH6 882
- #define NTCH7 990
- //列出全部C调的频率
- #define WHOLE 1
- #define HALF 0.5
- #define QUARTER 0.25
- #define EIGHTH 0.25
- #define SIXTEENTH 0.625
- //列出所有节拍
- int tune[]= //根据简谱列出各频率
- {
- NTC5,NTC5,NTC6,
- NTCH1,NTC6,NTC5,NTC6,NTCH1,NTC6,NTC5,
- NTC3,NTC3,NTC3,NTC5,
- NTC6,NTC6,NTC5,NTCH3,NTCH3,NTCH2,NTCH1,
- NTCH2,NTCH1,NTCH2,
- NTCH3,NTCH3,NTCH2,NTCH3,NTCH2,NTCH1,NTCH2,NTCH1,NTC6,
- NTCH2,NTCH2,NTCH2,NTCH1,NTC6,NTC5,
- NTC6,NTC5,NTC5,NTCH1,NTC6,NTC5,NTC1,NTC3,
- NTC2,NTC1,NTC2,
- NTC3,NTC5,NTC5,NTC3,NTCH1,NTC7,
- NTC6,NTC5,NTC6,NTCH1,NTCH2,NTCH3,
- NTCH3,NTCH2,NTCH1,NTC5,NTCH1,NTCH2,NTCH3,
- NTCH2,NTC0,NTCH3,NTCH2,
- NTCH1,NTC0,NTCH2,NTCH1,NTC6,NTC0,
- NTCH2,NTC6,NTCH1,NTCH1,NTCH1,NTC6,NTC5,NTC3,
- NTC5,
- NTC5,NTC6,NTCH1,NTC7,NTC6,
- NTCH3,NTCH3,NTCH3,NTCH3,NTCH2,NTCH2,NTCH1,
- NTC6,NTCH3,NTCH2,NTCH1,NTCH2,NTCH1,NTC6,
- NTCH1,
- };
- float durt[]= //根据简谱列出各节拍
- {
- 0.5,0.25,0.25,
- 1.5,0.5,0.5,0.25,0.25,0.5,0.5,
- 1+1+1,0.5,0.25,0.25,
- 1.5,0.5,0.5,0.5,0.25,0.25,0.5,
- 1+1+1,0.5,0.5,
- 0.5,0.5,0.5,0.25,0.25,0.5,0.25,0.25,0.5,
- 0.5,0.5,0.5,0.25,0.25,1+1,
- 0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,
- 1+1+1,0.5,0.5,
- 1.5,0.5,0.5,0.5,0.5,0.5,
- 1.5,0.5,1,0.5,0.25,0.25,
- 1.5,0.5,0.5,0.5,0.5,0.25,0.25,
- 1+1+1,0.5,0.25,0.25,
- 1,0.5,0.25,0.25,1,1,
- 0.5,0.5,0.5,0.5,1,0.25,0.25,0.5,
- 1+1+1+1,
- 0.5,0.5,0.5,0.5,1+1,
- 0.5,0.5,0.5,0.5,1.5,0.25,0.25,
- 1.5,0.5,1,0.25,0.25,0.25,0.25,1+1+1+1,
- };
- int length;
- int tonepin=8; //得用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(500*durt[x]); //这里用来根据节拍调节延时,500这个指数可以自己调整,在该音乐中,我发现用500比较合适。
- noTone(tonepin);
- }
- delay(2000);
- }
3、校验后上传到开发板中即可听到蜂鸣器播放的乐曲了。乐谱制作方法将在下一篇博客中进行分享,敬请关注。