ir servo 2 positions scan

Hi.
I m trying to scan in two angles using a servo . 90 & 180 degree to see if there is an obstacle.
What i v done so far is…

#include <Servo.h>

Servo myservo; // create servo object to control a servo

// a maximum of eight servo objects can be created

int pos = 0; // variable to store the servo position
int aDelay = 30;           // Delay for the servo and let the IR to return results
int readDistance1 ;         // Variable to keep IR readouts
int readDistance2 ;
int minDistanceLimit = 100 ;  // Distance to set as Obstacle
int sensorPin = 3;          // IR Sensore on Analog PIN 3

int green_led = 13;
int red_led = 9;

void setup()

{
pinMode(green_led, OUTPUT);
pinMode(red_led, OUTPUT);

myservo.attach(7); // attaches the servo on pin 9 to the servo object

}

void loop()
{
  digitalWrite(green_led, LOW);
  digitalWrite(red_led, LOW);
  delay (2000);
 
  set_vertical_flag ();
  
}

void set_vertical_flag ()
{

myservo.write(180);
readDistance1 = analogRead(sensorPin);  // Take a reading from sensor
delay(aDelay);

 if (readDistance1 > minDistanceLimit)   // If we can scan an obstacle
      {
        digitalWrite(green_led, HIGH);
        delay(1500);
      }
 else {digitalWrite(green_led, LOW);}     

delay(1500);


myservo.write(90);
readDistance2 = analogRead(sensorPin);
delay(aDelay);

if (readDistance2 > minDistanceLimit)   // If we can scan an obstacle
      {
        digitalWrite(red_led, HIGH);
        delay(1500);
      }
else  {digitalWrite(red_led, LOW);}

delay(1500);


}

Its my first time im trying to code and i know that my code is … :-[ :-[

There is something that i must modify ???
What can i do to make it more efficient ???

Thnx in advance.

In your sketch you have a delay after reading the sensor, it should be after the servo.write and before the sensor reading.

You may need a longer delay between writing the servo position and reading the distance, perhaps half a second or more to move the servo 90 degrees.

Thnx mem for your reply :) How can i smooth the results by taking an average of multiple readings ???

How can i smooth the results by taking an average of multiple readings ???
A simple way is to add multiple readings together and divide by the number of readings.

A simple way is to add multiple readings together and divide by the number of readings.

A sample of code ??? How can i do this ???

unsigned long avg;
for (int i = 0, avg = 0; i < N_READINGS; ++i) {
  avg += analogRead (whatever);
}
avg /= N_READINGS;

[ch932][ch919][ch925][ch935] !!!! AWOL... :)