// Define the pin number for the push button
const int startButton = 9;
const int stopButton = 8;
const int ledPin = 10;
const int buzzerPin = 11;
int melody[] = {
294, 294, 392, 330, 294, 247, 262,
294, 294, 392, 330, 294, 247, 262,
294, 330, 349, 294, 330, 349, 392,
262, 330, 294, 262, 220, 247, 262
};
int noteDuration[] = {
4, 8, 8, 4, 8, 8, 2,
4, 8, 8, 4, 8, 8, 2,
4, 8, 8, 4, 8, 8, 2,
4, 8, 8, 4, 8, 8, 2
};
int melodyLength = sizeof(melody) / sizeof(melody[0]);
int buttonState1 = LOW;
int buttonState2 = LOW;
int buzzerState = LOW;
int dt = 200;
// Setup function runs once when the program starts
void setup() {
// Set the button pin as an input with an internal pull-up resistor
pinMode(startButton, INPUT_PULLUP);
pinMode(stopButton, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Start the serial monitor at 9600 baud
Serial.begin(9600);
}
// The loop function runs repeatedly after setup()
void loop() {
// Read the current state of the button (HIGH or LOW)
buttonState1 = digitalRead(startButton);
buttonState2 = digitalRead(stopButton);
Serial.print(" startButton = ");
Serial.println(buttonState1);
Serial.print(" stopButton = ");
Serial.println(buttonState2);
/*
// Check if the button1 is currently pressed (LOW)
if (buttonState1 == LOW) {
//isPlaying = true; // Set playing state to TRUE
//buzzerState = !buzzerState;
//buzzerState = HIGH;
// Stop
//if(buzzerState == HIGH){
for(int i = 0; i < melodyLength; i++){
if (buttonState2 == LOW) {
//buzzerState = LOW;
break;}
int noteDurationMS = 1000 / noteDuration[i];
tone(buzzerPin, melody[i], noteDurationMS);
digitalWrite(ledPin, HIGH);
delay(noteDurationMS * 1.3);
noTone(buzzerPin);
digitalWrite(ledPin,LOW);
delay(noteDurationMS * 0.10);
// Stop
if (buttonState2 == LOW) {
buzzerState = LOW;
noTone(buzzerPin);
Serial.print("This is stopButton = ");
Serial.println(buttonState2);
break;
}
}
}
else{
noTone(buzzerPin);
digitalWrite(ledPin, LOW);
}
*/
if (buttonState1 == LOW && buttonState2 == HIGH) {
buzzerState = HIGH;
while(buzzerState == HIGH ){
for(int i = 0; i < melodyLength; i++){
int noteDurationMS = 1000 / noteDuration[i];
tone(buzzerPin, melody[i], noteDurationMS);
digitalWrite(ledPin, HIGH);
delay(noteDurationMS * 1.3);
noTone(buzzerPin);
digitalWrite(ledPin,LOW);
delay(noteDurationMS * 1);
if (buttonState2 == LOW) {
buzzerState = LOW;
noTone(buzzerPin);
Serial.print("This is stopButton = ");
Serial.println(buttonState2);
break; }
}
}
}
else{
noTone(buzzerPin);
buzzerState = LOW;
digitalWrite(ledPin, LOW);
}
}