#define PIN_TRIG 3
#define PIN_ECHO 2
const int l1 = 7;
const int b1 = 12;
void setup() {
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
pinMode(l1, OUTPUT); // Corrected: Set LED pin as OUTPUT
pinMode(b1, OUTPUT);
}
void loop() {
// Ensure the trigger pin is LOW before starting measurement
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
// Trigger the ultrasonic sensor
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10); // Corrected: Send 10µs pulse
digitalWrite(PIN_TRIG, LOW);
// Measure the response duration
long duration = pulseIn(PIN_ECHO, HIGH);
// Convert to distance
int distance_cm = duration / 58;
int distance_inch = duration / 148;
// Print distances
Serial.print("DISTANCE IN CM: ");
Serial.println(distance_cm);
Serial.print("DISTANCE IN inches: ");
Serial.println(distance_inch);
// LED control logic
if (distance_cm <= 100) {
digitalWrite(l1, HIGH);
Serial.println("Led on");
digitalWrite(b1, HIGH);
tone(b1,250);
} else {
digitalWrite(l1, LOW);
digitalWrite(b1, LOW);
Serial.println("Led off");
noTone(b1);
}
delay(1000); // 1 second delay
}
//code written by vel