I need help getting a button to activate an active buzzer using an arduino

I am trying to execute the following:

Button A is pressed, the buzzer is silent.

Button B is pressed, the buzzer is on at a predetermined frequency.

What has worked:

int buttonApin = 9;
int buttonBpin = 8;
int buzzer = 12;

void setup() {
   ///put everything to output
}

void loop() {
   if (digitalRead(buttonApin) == LOW)
   {
      digitalWrite(buzzer, LOW);
   }
   if (digitalRead(buttonBpin == LOW)
   {
      digitalWrite(buzzer, HIGH);
   }

This works fine. I push button A, there is no sound, then I push button B the buzzer is on and stays on until I push A again.

My issue is when I replace "digitalWrite(buzzer, High); with the following:

{
  digitalWrite(buzzer, HIGH);
  delay(1000);
  digitalWrite(buzzer, LOW);
  delay(1000); 
}

When I do this and I push button B, the buzzer only does the buzzer sound for 1 second. However, when I hold the buzzer down, it preforms as desired. How can I make it so that the buzzer will continue oscillating between high and low without having to hold the button B down, and until I again push button A signaling it to stop?

2 answers

  • answered 2019-11-14 07:17 Serve Laurijssen

    One options is to use a state variable and time which switches from on to off until button is pressed. You just keep looping and record the time. When the button A is pressed light is turned off and the code waits for a button B press. It does that forever.

    #define OFF 0
    #define ON 1
    #define BUTTON 2
    
    static char state = ON;
    static unsigned long prevTime = 0;
    
    void loop() {
       if (digitalRead(buttonApin) == HIGH)
       {
          state = BUTTON;
          digitalWrite(buzzer, LOW);
       }
       if (digitalRead(buttonBpin) == HIGH)
       {
          state = ON;
       }
    
       if (state != BUTTON && (millis() - prevTime >= 2000)) {
         digitalWrite(buzzer, HIGH);
         prevTime = millis();
         state = ON - state;
       } 
    }
    

  • answered 2019-11-15 00:42 Lemuel Tarrazona

    good day sir. may i check your schematic? i think you're connecting the buzzer and the button at the same ground. the buzzer's button should be separated from the buzzer so that the flow of electricity will not be cut if the buzzer was not pressed.