const int photoResistorPin = A0; // Photoresistor pin
const int buzzerPin = 9; // Passive buzzer pin
const int buttonPin = 10; // Button pin
const int dt = 200; // Wait for 200 ms before reading again
int photoValue = 0; // Analog value read from the photoresistor
int frequency = 0; // Tone frequency based on the photoresistor reading
bool soundOn = false; // Flag variable to turn sound on or off
void setup() {
pinMode(photoResistorPin, INPUT); // Set the photoresistor pin as input
pinMode(buzzerPin, OUTPUT); // Set the buzzer pin as output
pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as input with pull-up resistor
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Read the analog value from the photoresistor
photoValue = analogRead(photoResistorPin);
// Map the photoresistor reading to a frequency between 200 and 2000 Hz
frequency = map(photoValue, 0, 1023, 200, 2000);
// Check if the button is pressed
if (digitalRead(buttonPin) == LOW) {
soundOn = !soundOn; // Invert the value of the soundOn flag variable
}
// Generate the tone if the soundOn flag variable is true
if (soundOn) {
tone(buzzerPin, frequency); // Generate the tone
} else {
noTone(buzzerPin); // Stop the tone
}
// Print the photoresistor reading and frequency to the serial monitor
Serial.print("Photoresistor reading: ");
Serial.print(photoValue);
Serial.print(", Frequency: ");
Serial.println(frequency);
delay(dt); // Wait for 200 ms before reading again
}