 # Constrain function

Hi,

I am building a robot with multiple ultrasonic sensors (HC-SR04) for obstacle detection. As I have multiple sensors, I am using a common function getDistance() to find the distance by passing the sensor as an argument. I am using a library called "UltrasonicSensor" by Giuseppe Martini to compute the distance directly. The function distanceInMilllimeters() is a function of the library "UltrasonicSensor" which triggers the sensors, waits for echo, records the time, calculates and returns the distance in mm. Since the ultrasonic sensors are not so precise, I am using a basic average function to find a mean value of 3 sequential readings.

However, the sensors provide negative or unrelated values when the measured distance is out of the range (20-4000mm). To cut down on these values, I am using a constrain function to limit the values between (10-4000mm). But occasionally, I still get values beyond the constrained limits such as 16000 or 19000.

I don't understand how this is even possible. Any idea on solving this would be helpful.

Thanks.

``````int getDistance(UltrasonicSensor a){
unsigned int dist1,dist2,dist3,dist;
dist1=constrain(a.distanceInMillimeters(),10,4000);
dist2=constrain(a.distanceInMillimeters(),10,4000);
dist3=constrain(a.distanceInMillimeters(),10,4000);
dist=(dist1+dist2+dist3)/3;
return dist;
}
``````

This is stated in the Arduino reference for the constrain function:

"Because of the way the constrain() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results."

Try this:

``````int getDistance(UltrasonicSensor a){
int dist1,dist2,dist3,dist;
dist = a.distanceInMillimeters();
dist1=constrain(dist,10,4000);
dist = a.distanceInMillimeters();
dist2=constrain(dist,10,4000);
dist = a.distanceInMillimeters();
dist3=constrain(dist,10,4000);
dist=(dist1+dist2+dist3)/3;
return dist;
}
``````

Thanks.

I didn't notice that. I'll test and post the outcome.

Thanks again.

Abinav_Shankar: Thanks.

I didn't notice that. I'll test and post the outcome.

Thanks again.

No problem. I'll be interested to see if that corrects it.

I think that solved it.

No values above the constrained limits so far.

Thanks.

Abinav_Shankar: I think that solved it.

No values above the constrained limits so far.

Thanks.

Glad it worked out!