//code for testing Ultrasonic Module
#define ECHOPIN 3 // Pin to receive echo pulse
#define TRIGPIN 2 // Pin to send trigger pulse
#define Pin 9 // pin to LED Blink
void setup() {
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
pinMode(9,OUTPUT);
}
void loop() {
// Start Ranging -Generating a trigger of 10us burst
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
float distance = pulseIn(ECHOPIN, HIGH); // pulseIn returns microseconds, an unsigned long
distance= distance/58;
Serial.print(distance);
Serial.println(" cm");
delay(200);
if (distance < 5) {
digitalWrite(Pin 9, LOW);
delay(50);
digitalWrite(Pin 9,HIGH);
delay(50)
}
else
{
digitalWrite(Pin 9, LOW)
}
} // end of loop
How does knowing how long the returned pulse is high tell you distance?
I would think you’d need to measure from the time you sent the pulse to the time you saw the pulse return to get a distance. So you really want edge detection, not width detection, yes?
CrossRoads:
How does knowing how long the returned pulse is high tell you distance?
That's how the HC-SR04 ultrasonic rangefinders work. They delay the start of the Echo pulse a few microseconds to allow time for the pulseIn() call. Then when the echo arrives they delay the end of the Echo pulse the same amount. The old Paralax "PING)))" sensor works the same but uses a single pin for both input and output.