I am working on a system to make a random song play from a piezo-buzzer whenever a door opens. I am taking this step by step. At the moment I am working on getting a button to activate a song that will play and stop.
I tried a while loop, but could only get my tune to play while I was holding the button down. I need it to play through and stop at the last note.
The tune is playing but is going in an endless loop. I don't know why the button does not do anything at the moment. I have tried implementing an if-statement, but it's being ignored by the program. What can I do to make this work?
This is what I have come up with so far:
#include "pitches.h"
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
};
const int buttonPin = 2;
const int buzzerPin = 9;
int buttonState = 0;
void setup()
{
pinMode (buttonPin, INPUT);
pinMode (buzzerPin, OUTPUT);
}
void loop()
{
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH);
{
song();
}
}
void song()
{
for (int thisNote = 0; thisNote < 8; thisNote++)
{
int noteDuration = 1000 / noteDurations[thisNote];
tone (buzzerPin, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(buzzerPin);
}
}