const int potPin = 13; // The analog pin connected to the potentiometer
const int buzzerPin = 32; // The digital pin connected to the buzzer
const int buttonPin = 4; // The digital pin connected to the push button
int buttonState = 0; // variable for reading the pushbutton status
boolean soundEnabled = true; // variable to control sound on/off state
void setup() {
pinMode(buzzerPin, OUTPUT); // Set the buzzer pin as an output
pinMode(buttonPin, INPUT); // Set the push button pin as an input
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Read the state of the pushbutton value
buttonState = digitalRead(buttonPin);
// Check if the button is pressed to toggle sound on/off
if (buttonState == HIGH) {
soundEnabled = !soundEnabled; // Toggle the sound state
delay(250); // Add a small delay to debounce the button
}
// Only generate sound if sound is enabled
if (soundEnabled) {
int sensorValue = analogRead(potPin); // Read the value from the potentiometer
int volume = map(sensorValue, 0, 1023, 0, 255); // Map the potentiometer value to the volume range
// Generate sound with the buzzer
tone(buzzerPin, volume); // Generate a tone with the given volume
delay(10); // Adjust the delay to control the speed of volume change
Serial.print("Potentiometer Value: ");
Serial.print(sensorValue);
Serial.print(" - Volume: ");
Serial.println(volume);
} else {
noTone(buzzerPin); // Turn off the buzzer if sound is disabled
}
}