//喇叭控制接腳
const int speaker = 7;
//樂曲速度
int tempo=250;
//低音頻率表 lfreqs[1]=>低音Do
int lfreqs[] = {0,131,147,165,175,196,220,247};
//中音頻率表 freqs[1]=>Do
int freqs[] = {0,262,294,330,349,392,440,494};
//高8度音頻率表 hfreqs[1]=>高音Do
int hfreqs[] = {0,523,587,659,698,784,880,988};
//高16度音頻率表 shfreqs[1]=>高16度音Do
int shfreqs[] = {0,1046,1175,1318,1397,1568,1760,1976};
float song[]={
//音階,拍子
5,1,3,1,3,2,
4,1,2,1,2,2,
1,1,2,1,3,1,4,1,
5,1,5,1,5,2,
5,1,3,1,3,2,
4,1,2,1,2,2,
1,1,3,1,5,1,5,1,
3,3,0,1,
2,1,2,1,2,1,2,1,
2,1,3,1,4,2,
3,1,3,1,3,1,3,1,
3,1,4,1,5,2,
5,1,3,1,3,2,
4,1,2,1,2,2,
1,1,3,1,5,1,5,1,
1,4
};
void setup() {
pinMode(speaker,OUTPUT);
}
void loop() {
//計算陣列長度
int num=sizeof(song)/sizeof(float);
int freq;
for(int i=0;i<num;i+=2){
if(song[i]>10){
//高音 10=>Do 20=>Re
freq=hfreqs[int(song[i]/10)];
}else if(song[i]<1 && song[i]>0){
//低音 0.1=>Do 0.2=>Re
freq=lfreqs[int(song[i]*10)];
}else{
//中音 1=>Do 2=>Re
freq=freqs[int(song[i])];
}
tone(speaker,freq,song[i+1]*tempo);
delay(song[i+1]*tempo);
delay(tempo/20);
}
while(1){
delay(1000);
}
}