#define trigPin 9
#define echoPin 10
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance <= 40) {
Serial.println("Object detected within 40 cm");
}
delay(500);
}
Welcome!
Sorry but what is your question?
What is the hardware it is going to run on?
What other hardware is involved.
With some more information we may be able to help you.
...and please DON'T copy your code as the topic title, use any short summary of the problem or target, it helps users to know what you're talking about even from the topics list.
Please edit your first post here and change topic title with something relevant, and add more information as @gilshultz kindly requested.