// 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
}
$abcdeabcde151015202530fghijfghij
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
ultrasonic1:VCC
ultrasonic1:TRIG
ultrasonic1:ECHO
ultrasonic1:GND
bz1:1
bz1:2
led1:A
led1:C
r1:1
r1:2