I'm trying to make it so a single pushbutton press will trigger a passive piezo buzzer to sound for around 1 second, but I have no Idea what to do. I have made it so the buzzer can react to a single button press but I can't code the functions to be active for as long as I need.
Here is the code that I'm currently at right now.
int buttonPin = 8;
int buzzerPin = 5;
int pitchVal = 2;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT_PULLUP);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
bool currentStateButton = digitalRead(buttonPin);
if (currentStateButton == LOW) {
digitalWrite(buzzerPin, HIGH);
delay(2);
digitalWrite(buzzerPin, LOW);
delay(2);
while (digitalRead(buttonPin) == LOW) {}
}
}
This allows only one oscillation to come from the button press. Is there any way for me to loop the digitalWrite/ delay functions for a longer sound?
First lesson: don't use delay(). The reason? While delay() is doing its thing all your other code is inactive - things like checking buttons, setting outputs, etc.
Become familiar with the first five concepts in IDE -> file/examples/digital/, especially blink without delay. Many other resources/tutorials exist on the web discussing this.
Sorry for not resolving the topic but I solved my issue. I tried using the tone() function as groundfungus recommended in addition to the single button press code and it worked perfectly. Here's my new code.
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT_PULLUP);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
bool currentStateButton = digitalRead(buttonPin);
if (currentStateButton == LOW) {
tone(buzzerPin, 300, 500);
while (digitalRead(buttonPin) == LOW) {}
}
}