Distance measurement using ultrasonic sensor

Hi,
Using the ultrasonic module, I was trying to measure distance (water level in a tank). I settled up two ultrasonic sensors (HR-SR04) for getting more accurate data, but I'm getting the same value for the below code. I can't understand why the sensors/modules are providing the same distance even though they are placed at different known distances. I'm using Arduino Mega 2560 device.

const int trigPin1 = 33;
const int echoPin1 = 35;
const int trigPin2 = 32;
const int echoPin2 = 34;

long duration1;
int distance1;
long duration2;
int distance2;

void setup() {
  Serial.begin(9600); 
  pinMode(trigPin1, OUTPUT); 
  pinMode(echoPin1, INPUT); 
  pinMode(trigPin2, OUTPUT); 
  pinMode(echoPin2, INPUT); 
}

void loop() {
  
  digitalWrite(trigPin1, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1 * 0.034 / 2)+1;
  
  digitalWrite(trigPin2, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2 = (duration1 * 0.034 / 2)+1;
  
  Serial.print(distance1); Serial.print(",");
  Serial.print(distance2);
  Serial.println();
  delay (5000);
}

Look at duration. You need to be careful with copy and paste.

1 Like

Check your code again there is mistake there pls identify it in duration

1 Like

In addition to that, I'd put a delay between taking the readings, to allow the echoes of the first ping to decay sufficiently to not cause false readings on the second ping.

1 Like

Yes delay can be helpful but including delays resulting in slow proccesing

There are more ways

There's already a five second delay between pairs of readings.
I'm talking about 30 to 50 milliseconds

In the program delay is for loop not in between for sensor reading

Welcome to my ignore list

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.