const int trigPin = 2; // Ultrasonic sensor trig pin
const int echoPin = 3; // Ultrasonic sensor echo pin
const int ledPin = 13; // LED pin
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
long duration, distance;
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate distance
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn on LED if distance is less than 20cm
if (distance < 20) { // Adjust this threshold as needed
digitalWrite(ledPin, HIGH); // LED ON (lid closed)
} else {
digitalWrite(ledPin, LOW); // LED OFF (lid open)
}
delay(1000); // Adjust delay as needed
}