Motion detection with ultrasound sensor SR04

Hi all,

I got a ultrasonic sensor SR04 and I want to create a simple project with it, which is a motion detector to trigger a photo camera.
I thought it could work like this:

1-Place the sensor a fix it somewhere against a fix object (wall, or whatever).
2-Take some readings of the distance and make an average of it
3-The monitor the distance and if the read distance drops from the average (by some factor) then trigger the camera.

I thought it was pretty straight forward but I came to an issue I don’t know how to address. My sketch is the following:

#define trigPin 13
#define echoPin 14

int mean;
int totalMean;
int duration, distance;
 
boolean calibrated=false;
boolean waited=false;


void setup() {

  Serial.begin(9600);
  
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
}


void distanceCalculator(){

      digitalWrite(trigPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(trigPin, LOW);
      
      duration=pulseIn(echoPin, HIGH);
      distance=(duration/2)/29.1;
  
}



void loop(){
  
     
     if (calibrated==false){
       calibrate();
     }else{

     distanceCalculator();
    
     //delay(100);
     
     if (distance<0.90*totalMean){

     Serial.print(" Shoot ");     
     Serial.println(distance);

     }
    }
    
 }



void calibrate(){

  mean=0;
  totalMean=0;
  
    for(int i=1; i<101; i++){

      distanceCalculator();
     
       mean=mean+distance;
       
       delay(50);
               
       if (i==100) totalMean=mean/i; 
           
     }
  
      Serial.println(distance);
      
      calibrated=true;
      Serial.println("");
      Serial.print(totalMean);
      Serial.println(" Calibrated!");

}

with this code the calibration works ok. However, when the loop goes into “monitoring” (calibrated==true), the readings are erroneous, and the Serial Monitor goes crazy printing small distances. If I add a delay (commented out above) it gets better. Not perfect, but better.

I would like to know what am I missing here. Any ideas?

Thanks in advance!