2014-02-10 2 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

loop() 內 播放 音樂, 동시;에서 타이머 중간 셧다운 콜백() 內制 LED 閃예 : Timer1.attachInterrupt (callback);

루프() 기능에서 멜로디를 연주하고 타이머 인터럽트 기능에서 LED를 동시에 깜박임. 예 : Timer1.attachInterrupt (콜백);

관련 문제