2014-02-10 107 views
1

這是我的代碼,一切工作正常,但我不知道如何讓我創建的旋律循環?另一個問題是,如何在旋律播放時讓LED同時閃爍?Arduino旋律循環?

#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); 
} 

回答

0

簡單地把你的代碼獨立的函數裏,並從循環中調用它:

#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 language book like the K&R,讀對於C語言編程的基礎知識,有很多需要了解的內容。

-2

在環()內播放音樂,同時,在定時器中斷程式回調()內控制LED閃爍 例:Timer1.attachInterrupt(回調);

在循環()函數中播放旋律並同時閃爍定時器中斷功能中的LED。例如: ex:Timer1.attachInterrupt(callback);