Back to Parent

// Define a pin we'll place an LED on
int ledPin = D2;

// Our button wired to D0
int buttonPin = D3;

int speaker = D4;

int melody[] = {1908,2551,2551,2273,2551,0,2024,1908};

int noteDurations[] = {4,8,8,4,4,4,4,4 };

void setup()
{
  // Set up the LED for output
  pinMode(ledPin, OUTPUT);

  // For input, we define the
  // pushbutton as an input-pullup
  // this uses an internal pullup resistor
  // to manage consistent reads from the device
  
  pinMode( buttonPin , INPUT_PULLUP); // sets pin as input
  
  pinMode(speaker, OUTPUT);
}

void loop()
{
    // find out if the button is pushed
    // or not by reading from it.
    int buttonState = digitalRead( buttonPin );

    if( buttonState == LOW )
    {
     // turn the LED On
     digitalWrite( ledPin, HIGH);
     for (int thisNote = 0; thisNote < 8; thisNote++) {

      int noteDuration = 1000/noteDurations[thisNote];
      tone(speaker, melody[thisNote],noteDuration);

      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      
      noTone(speaker);
     }
      
    }else{
     // otherwise
     // turn the LED Off
     digitalWrite( ledPin, LOW);
     noTone(speaker);

    }

}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0