#define TRIG_PIN 3
#define ECHO_PIN 4 // Make sure to define ECHO_PIN
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
float readDistanceCM() {
// Trigger the ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the echo
int duration = pulseIn(ECHO_PIN, HIGH);
// Convert duration to distance in centimeters
return duration * 0.034 / 2;
}
void loop() {
// Read the distance from the ultrasonic sensor
float distance = readDistanceCM();
// Check if an object is within 100 cm
bool isNearby = distance < 100;
// Turn the LED on or off based on proximity
digitalWrite(LED_BUILTIN, isNearby ? HIGH : LOW);
// Print the measured distance to the Serial Monitor
Serial.print("Measured distance: ");
Serial.print(distance);
Serial.println(" cm");
// Small delay to prevent spamming the Serial Monitor
delay(100);
}