const int ldrPin = A0; // LDR connected to analog pin A0
const int buttonPin = 2; // Button connected to digital pin 2
const int speakerPin = 9; // Speaker connected to digital pin 9
const int ledPin = 13; // LED connected to pin 13
// Dramatically different frequencies (non-musical)
int notes[] = {100, 300, 600, 900, 1200, 2000, 3000};
void setup() {
pinMode(buttonPin, INPUT); // Button logic: HIGH when pressed
pinMode(speakerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int buttonState = digitalRead(buttonPin); // Read the button
if (buttonState == HIGH) {
int lightLevel = analogRead(ldrPin); // Read LDR
int noteIndex = map(lightLevel, 0, 1023, 6, 0); // Bright = low note
noteIndex = constrain(noteIndex, 0, 6); // Keep within range
int frequency = notes[noteIndex]; // Pick frequency
tone(speakerPin, frequency); // Play note
digitalWrite(ledPin, HIGH); // LED on
Serial.print("Light: ");
Serial.print(lightLevel);
Serial.print(" | Frequency: ");
Serial.println(frequency);
} else {
noTone(speakerPin); // No sound
digitalWrite(ledPin, LOW); // LED off
}
delay(100);
}