# include & lt; Servo. H>//servo library
Servo Servo;//create steering gear object to control steering gear
Int trigPin=5;
Int echoPin=6;
Int servoPin=7;
Int led=10;
Long duration, dist, business;
Long aver [3].//array for business,
Void setup () {
//initialize serial port communication and connection SR04 pin
Serial.begin(9600);
Servo. Attach (servoPin);//the connection on the pin 7 gives the steering gear servo control of the
PinMode (trigPin, the OUTPUT);//to detect the pulse width of input pin, need to be set to the input state
PinMode (echoPin, INPUT);
Servo. Write (0);//close cap on power on
Delay (500)
Servo. Detach ();
}
Void measure () {
DigitalWrite (10, HIGH);
DigitalWrite (trigPin, HIGH);//create a 10 us high pulse to trigger TrigPin
delayMicroseconds(2);
DigitalWrite (trigPin, LOW);
DelayMicroseconds (5);
DigitalWrite (trigPin, HIGH);
PinMode (echoPin, INPUT);
Duration=pulseIn (echoPin, HIGH);
Dist=(duration/2)/10;//obtain short detection pulse width and measure distance
}
Void loop () {
for (int i=0; i<=2; I++) {//business, short
Measure ().
Aver [I]=dist.
delay(10);//delay between measurements
}
Dist=(aver aver [0] + [1] + aver [2])/3;
If (dist<50) {
//Change short as per your need
Servo. Attach (servoPin);
delay(1);
Servo. Write (0);
Delay (3000);
Servo. Write (150);
delay(1000);
Servo. Detach ();
}
Serial. Print (dist);
}