I want to stop the sound of a buzzer after I push the push button. I tried a code, but when the button is not pushed, the buzzer continue to make sound. How can I fixed it?
const int pin_contact= 6;
const int buzzer = 9; //buzzer to arduino pin 9
void setup(){
pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
pinMode(pin_contact, INPUT);
Serial.begin(9600);
}
void loop() {
tone(buzzer, 200);
int stare_contact = digitalRead(pin_contact);
if (stare_contact == HIGH) {
noTone(buzzer);
}
}
loop()
so as soon as you stop pushing the button, the sound starts again. The simplest solution would be to move thetone (buzzer, 200);
command out ofloop()
and place it at the end ofsetup()
. Also make sure your button actually reads “HIGH” when pressed. Many buttons are active “LOW”.