My Buzzer Beeps Randomly

My Code:

const int buttonPin = 11;  // Pin number where the button is connected

void setup() {
  pinMode(buttonPin, INPUT);  // Set the button pin as an input
  pinMode(A0, OUTPUT); // Set the buzzer pin as an output
  pinMode(A5, OUTPUT);
  tone(A0, 1000, 2000);
}

void loop() {
  int buttonState = digitalRead(buttonPin); // Read the state of the button

  if (buttonState == HIGH) {  // If the button is pressed
    pinMode(A5, OUTPUT);
    analogWrite(A5, 150); // G4
    delay(100);
  } else if (buttonState == LOW) {
    pinMode(A5, INPUT);
    analogWrite(A5, 0); // G4
    delay(100);
  }
}

Congratulations for getting your buzzer to beep randomly.

1 Like

Spend more time studying the tone() function to see how to use it.

You probably do not have a pull-up or pull-down resistor on your switch, leaving the input floating when the switch is open.

Add this resistor or use INPUT_PULLUP.

Hard to tell what your problem is, post an annotated schematic showing how it is wired and note any wires over 10"/25cm in length.

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