The sensor will always return 0 then the true distance.
Below is the code:
#define echoPin 7
#define trigPin A2
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
Below is the output:
...
10:46:42.344 -> Distance: 8 cm
10:46:43.020 -> Distance: 0 cm
10:46:43.020 -> Distance: 8 cm
10:46:43.687 -> Distance: 0 cm
10:46:43.731 -> Distance: 8 cm
10:46:44.412 -> Distance: 0 cm
10:46:44.412 -> Distance: 8 cm
10:46:45.100 -> Distance: 0 cm
10:46:45.100 -> Distance: 8 cm
10:46:45.804 -> Distance: 0 cm
10:46:45.804 -> Distance: 8 cm
10:46:46.501 -> Distance: 0 cm
...
It might be wise to try a delay of x time. I'd start with delay(10) and work up from there till a good delay time has been reached.
A delay using millis() would not stop the rest of loop() from running.
unsigned long sr04Interval = 10;
unsigned long pastsro4Time;
//
void loop() {
if( (millis() - pastsro4Time) >= sro4Interval )
{
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
pastsro4Time = millis();
} //if( (millis() - pastsro4Time) >= sro4Interval )
distance=0; // something to do when not pinging
}
something like that, not tested.
the op might want to consider setting a timeout value for pulse in of less than a second pulseIn(pin, value, timeout)
The OP might consider the mixed data types used to determine distance and the possibility of error introduction.
Here the OP declares int distance; // variable for the distance measurement an int.
Here the OP declared long duration; a long int.
Here the OP does mixed data type math distance = duration * 0.034 / 2; The OP might benefit from making distance into a float and doing distance = (float)duration * 0.034 / 2.0;