// Define pin numbers
const int trigPin = 26;
const int echoPin = 27;
const int ledPin = 13;
const int buzzerPin = 12;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
pinMode(ledPin, OUTPUT); // LED pin as OUTPUT
pinMode(buzzerPin, OUTPUT); // Buzzer pin as OUTPUT
Serial.begin(9600); // Initialize serial communication
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Calculate the distance
if (distance < 20) { // Check if the distance is less than 20 cm
digitalWrite(ledPin, HIGH); // Turn the LED on
playMelody(); // Play melody on the buzzer
} else {
digitalWrite(ledPin, LOW); // Turn the LED off
noTone(buzzerPin); // Stop any tone being played
}
delay(100); // Delay a little bit to improve simulation
}
void playMelody() {
tone(buzzerPin, 262, 200); // Play C note for 200 ms
delay(200); // Delay 200 ms
tone(buzzerPin, 294, 200); // Play D note for 200 ms
delay(200); // Delay 200 ms
tone(buzzerPin, 330, 200); // Play E note for 200 ms
delay(200); // Delay 200 ms
tone(buzzerPin, 349, 200); // Play F note for 200 ms
delay(200); // Delay 200 ms
}