// Constants for pin assignments
const int speakerPin = 9; // Pin connected to the speaker or piezo buzzer
// Variables for frequency and tone duration
int frequency = 1000; // Frequency in Hertz (initial tone frequency)
int duration = 1000; // Duration in milliseconds
void setup() {
// Set the speaker pin as an output
pinMode(speakerPin, OUTPUT);
}
void loop() {
// Generate the tone at the specified frequency
generateTone(speakerPin, frequency, duration);
// Wait for 1 second before the next tone
delay(1000);
// Change frequency for the next tone (optional)
frequency += 100;
if (frequency > 2000) {
frequency = 1000; // Reset to initial frequency
}
}
// Function to generate a tone on the given pin
void generateTone(int pin, int frequency, int duration) {
int period = 1000000 / frequency; // Period in microseconds
int halfPeriod = period / 2; // Half the period
// Calculate how many cycles to play within the duration
long cycles = (long)frequency * duration / 1000;
for (long i = 0; i < cycles; i++) {
digitalWrite(pin, HIGH); // Set pin high
delayMicroseconds(halfPeriod); // Wait half period
digitalWrite(pin, LOW); // Set pin low
delayMicroseconds(halfPeriod); // Wait half period
}
}