2015-11-25 54 views
0

我想知道我可以如何在一个代码中合并我的LED和piezzo蜂鸣器。我想在按下按钮时立即停止音乐,并在同一时刻打开指示灯(LED)。 我的代码不能正常工作,您能否告诉我该怎么办?如何将一个LED和一个piezzo与arduino上的按钮结合使用?

 int buttonState = 0; 
     int speakerPin = 10; 
     int buttonPin= 7; 
     int frequency = 500; 
     int ledPin = 13; 
     int length = 17; // the number of notes 
     char notes[] = "gcefgcefgcefgcefga "; // a space represents a rest 
     int beats[] = {2,2,1,1,2,2,1,1,2,2,1,1,2,2,1,1}; 
     int tempo = 250; 

     void setup() {    
     pinMode(speakerPin, OUTPUT); 
     pinMode(ledPin, OUTPUT); 
     pinMode(buttonPin,INPUT); 
     } 

     void loop() { 
     buttonState = digitalRead(buttonPin); 

     if (buttonState==HIGH){ 
      digitalWrite(ledPin, HIGH); 
      noTone(speakerPin); 
     }else { 
      char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' }; 
      char notes[] = "gcefgcefgcefgcefga ";   
      digitalWrite(ledPin, LOW); 
      digitalWrite(speakerPin,HIGH); 
      if (long i = 0; i < duration * 5000L; i += tone * 15) { 

      } 

     void playTone(int tone, int duration) { 

      for (long i = 0; i < duration * 5000L; i += tone * 15) { 
      if (buttonState==LOW){ 
      digitalWrite(speakerPin, HIGH); 
      delayMicroseconds(tone); 
      digitalWrite(speakerPin, LOW); 
      delayMicroseconds(tone); 
      } 
     } 
     } 

     }} 
+0

哪里没有定义?为什么包括playTone如果你不使用它?哪个板子? – lxx

+0

if(long i = 0; i jabujavi

回答

1

可能有几个不同的原因,为什么你的代码不工作。 对于初学者来说:你还没有定义noTone,我没有看到普雷通公司实际使用,但在较高的水平,你正在试图做的是很简单,这个伪应该有所帮助:

void loop() { 
    buttonState = digitalRead(buttonPin); 
    if buttonState==LOW 

    playTone(); 
    digitalWrite(ledPin, LOW); 
    else {break out of loop} 
    //add in your pause here 
    delayMicroseconds(pause);//I'm not sure why you put tone here in your code, just initialize int of 1000 or something 

} 

你收到!希望这可以帮助!

相关问题