在Arduino中,有很多函数和库,tone就是其中一个,这个函数可以模拟不同的频率从而使蜂鸣器发出不同的声音。曾经,在课堂上展示过一个7个按键的小品,但是由于时间关系没有作代码检查,最后一个音高出实际100hz,真是遗憾。
由于没有更多的硬件,所以只演示了tone函数的使用:
/*
Name: Sketch1.ino
Created: 2019/2/11 17:16:22
Author: Administrator
*/
#define NTD1 294
#define NTD2 330
#define NTD3 350
#define NTD4 393
#define NTD5 441
#define NTD6 495
#define NTD7 556
#define NTDL1 147
#define NTDL2 165
#define NTDL3 175
#define NTDL4 196
#define NTDL5 221
#define NTDL6 248
#define NTDL7 278
#define NTDH1 589
#define NTDH2 661
#define NTDH3 700
#define NTDH4 786
#define NTDH5 882
#define NTDH6 990
#define NTDH7 112
uint8_t PinViolin = 6;
int NTD[21] = { NTD1, NTD2, NTD3, NTD4, NTD5, NTD6, NTD7,
NTDL1,NTDL2,NTDL3,NTDL4,NTDL5,NTDL6,NTDL7,
NTDH1 ,NTDH2 ,NTDH3 ,NTDH4 ,NTDH5 ,NTDH6 ,NTDH7 };
int curIDX = 0;
// the setup function runs once when you press reset or power the board
void setup() {
pinMode(PinViolin, OUTPUT);
}
// the loop function runs over and over again until power down or reset
void loop() {
for (int i = 0; i <sizeof(NTD); i++) {
tone(PinViolin,NTD[i],300);
delay(500);
noTone(PinViolin);
}
delay(1000);
}
这个函数有三个参数:
1、输出引脚
2、频率
3、发音时常
注意:delay(500),这样就导致发音300ms而后停顿200毫秒。