// Pin definitions
const int trigPin = 5;
const int echoPin = 18;
const int redLEDPin = 16;
const int greenLEDPin = 17;
const int buzzerPin = 4;
// Variables
long duration;
int distance;
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Initialize pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redLEDPin, OUTPUT);
pinMode(greenLEDPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Start with green LED on and red LED off
digitalWrite(greenLEDPin, HIGH);
digitalWrite(redLEDPin, LOW);
digitalWrite(buzzerPin, LOW);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Check if the distance is less than a threshold (e.g., 50 cm)
if (distance < 50) {
// Intruder detected
digitalWrite(greenLEDPin, LOW);
digitalWrite(redLEDPin, HIGH);
// Play a simple melody
tone(buzzerPin, 1000); // Play tone at 1000 Hz
delay(200);
tone(buzzerPin, 1500); // Play tone at 1500 Hz
delay(200);
tone(buzzerPin, 2000); // Play tone at 2000 Hz
delay(200);
noTone(buzzerPin); // Stop the tone
} else {
// No intruder
digitalWrite(greenLEDPin, HIGH);
digitalWrite(redLEDPin, LOW);
noTone(buzzerPin); // Ensure the buzzer is off
}
// Wait for a short period before the next loop
delay(500);
}
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
led1:A
led1:C
led2:A
led2:C
bz1:1
bz1:2