这是我的代码,一切都很好,除了我不知道如何得到我创造的旋律循环?另一个问题是,我如何使LED同时闪烁的旋律播放?
#include "pitches.h"
int led = 9;
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4
};
int noteDurations[] = { 4, 8, 8, 4,4,4,4,4 };
void setup() {
pinMode(led, OUTPUT);
// 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() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}发布于 2014-02-10 00:19:56
只需将代码放在独立的函数中,然后从循环中调用它:
#include "pitches.h"
int led = 9;
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4
};
int noteDurations[] = { 4, 8, 8, 4,4,4,4,4 };
void play_melody();
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
// keep the LED on while the melody's playing
play_melody();
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
// pause for one second between each melody iteration (you can remove this for continuous playing)
delay(1000);
}
void play_melody() {
// 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);
}
return;
}如果您不知道函数调用,我建议您打开一个C语言书籍,如K&R,并阅读它,您可以在其中学习C语言编程的基础知识。
发布于 2016-05-25 15:45:11
在循环()內播放音樂,同時;在Timer中斷程式回调()內控制內控制閃爍例:Timer1.attachInterruption(回调);
在循环()函数中播放旋律,同时在计时器交互功能中闪烁LED。例:Timer1.attachInterruption(回调);
https://stackoverflow.com/questions/21666952
复制相似问题