Help needed with piezo buzzer code

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.

Look in the reference for the tone() function. It will send a square wave to a selected pin of the specified frequency for a given time.

I agree with @dougp that learning to do without delay() is an important and worthwhile goal.
Non-blocking timing tutorials:
Blink without delay().
Blink without delay detailed explanation
Beginner's guide to millis().
Several things at a time.

1 Like

You can use ezBuzzer, a non-blocking library for piezo buzzer

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) {}
}

}

This is blocking code, like delay().
Look at the StateChangeDetection example in the IDE for a non-blocking example.
Leo..

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.