// Define Pins
const int TRIGGPIN = 4;
const int ECHOPIN = 5;
const int LED1 = 13;
long duration;
int distance;
void setup() {
Serial.begin(115200);
pinMode(TRIGGPIN, OUTPUT);
pinMode(ECHOPIN, INPUT);
pinMode(LED1, OUTPUT);
Serial.println("hi");
}
void loop() {
digitalWrite(TRIGGPIN, LOW);
delayMicroseconds(2);
// Sets the tRIGGPIN on HIGH state for 10 micro seconds
digitalWrite(TRIGGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGPIN, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(ECHOPIN, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(1000);
if (distance < 100) {
digitalWrite(LED1, HIGH);
}
else {
digitalWrite(LED1, LOW);
}
}