Loop upon powering.

This is an automatic trash bin. One HCSR-04 Ultrasonic sensor controls a SG90 servomotor that opens the lid while the other sensor indicates when the bin is full with a LED. It works fine at times and at others it powers the motor directly without there being any presence in front of the sensor over and over again. Is it the code?
This is the code I am using:

#include <Servo.h>   
Servo servo;     
int trigPin = 5;    
int echoPin = 6; 
int trigPin2 = 8;  
int echoPin2 = 9;
int servoPin = 10;
int LED1= 7;
long duration, dist, average;   
long aver[3];   




void setup() {       
   Serial.begin(9600);
   servo.attach(servoPin);  
   pinMode(LED1,OUTPUT);
   pinMode(trigPin, OUTPUT);  
   pinMode(echoPin, INPUT);  
   pinMode(trigPin2, OUTPUT);
   pinMode(echoPin2, INPUT);
   servo.write(0);         
   delay(100);
   servo.detach(); 
} 
void loop() {
 int bduration, bdistance;
 digitalWrite(trigPin2, LOW);
 delayMicroseconds(4);
 digitalWrite(trigPin2, HIGH);
 delayMicroseconds(10);
 bduration = pulseIn(echoPin2, HIGH);
 bdistance = (bduration/2) / 29.1;

 int duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(4);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;

 if (distance < 10)
 {
servo.attach(servoPin);
 delay(1);
servo.write(120);  
delay(7000);       
servo.write(0);    
delay(1000);
servo.detach();  
 }
  if (bdistance < 16)
 {
   digitalWrite(LED1, HIGH);
 }
 else 
 {
    digitalWrite(LED1, LOW);
 }
 delay(50);
}

You can answer your own question by using Serial.print() to look at the values used in your program logic. Called "debugging".

Paul

Please edit your post to add code tags.

 int bduration, bdistance;
  int duration, distance;

You are using int data type for duration. That could result in negative values for duration and distance. Better to use unsigned long for duration.

Also, you can add a third argument to the pulseIn() function to set a timeout different than the (one second) default.

pulseIn(pin, value, timeout);

I usually use 20000 to 30000 for the timeout as the sensor can’t detect accurate range much farther than that.

The pulseIn() function returns 0 for a timeout. May need to program for that eventuality.