I am trying to incorporate a button, buzzer, and 3 LEDs with a nano for a project. I have prototyped the circuit on a breadboard and am sure that the connections are correct. I want the buzzer to play a tune and the LEDs to turn on when the button is pressed is pressed for 3 seconds. The buzzer and LEDs work, just not when I want them to. For some reason, I press the button once for half a second and let go, and then the tune and LEDs trigger on a continuous loop even when the button is not pressed. Any advice?
`//Pins
int piezo=4; // Passive buzzer, Digital Pin 4
int led1=2; // First LED, Digital Pin 2
int led2=12; // Second LED, Digital Pin 12
int led3=9; // Third LED, Digital Pin 13
int button=6; // Momentary button, Digital Pin 6
//Button
unsigned long buttonTime; // Time that button has been pressed
int buttonState = 0; // Initial button state
//Counter
int counter=0; // counter starts at 0
void setup() {
pinMode(piezo, OUTPUT); // Sets Digital Pin 4 as an output
pinMode(led1, OUTPUT); // Sets Digital Pin 2 as an output
pinMode(led2, OUTPUT); // Sets Digital Pin 12 as an output
pinMode(led3, OUTPUT); // Sets Digital Pin 9 as an output
pinMode(button, INPUT); // Sets Digital Pin 6 as an input
}
void loop() {
buttonState = digitalRead(button); // buttonState is equivelant to whatever is read from the button, HIGH or LOW
if (buttonState == HIGH) {
counter++; // If the button is pressed, the counter begins counting upwards
}
if (counter >= 3000) {
digitalWrite(led1, HIGH); // Turns LED 1 on
digitalWrite(led2, HIGH); // Turns LED 2 on
digitalWrite(led3, HIGH); // Turns LED 3 on
tone(piezo,410,200); //Beginning of tune played by passive buzzer
delay(200);
tone(piezo,300,200);
delay(200);
tone(piezo,410,200);
delay(200);
tone(piezo,550,150);
delay(150);
tone(piezo,410,200);
delay(200);
tone(piezo,300,200);
delay(200);
tone(piezo,410,200);
delay(200);
tone(piezo,300,150);
delay(150);
tone(piezo, 100);
delay(200);
tone(piezo, 250);
delay(1000);
noTone(piezo); // End of tune played by passive buzzer
digitalWrite(led1, LOW); // Turns LED 1 off
digitalWrite(led2, LOW); // Turns LED 2 off
digitalWrite(led3, LOW); // Turns LED 3 off
}
else if (buttonState == LOW) {
counter=0; // Counter remains at 0 if the button is not pressed
}
}`
