Sharp IR and Servo

Why have you got a 1 millisecond delay at the end of your loop?

by accident I was looking for similar projects to mine and I tweaked the code and missed the delay

So I tried the code and now the servo stays at 180 degrees it doesn't return back to 0 after 2 seconds

#include <Servo.h>

Servo myservo1; //first servo

int SHARP_IR_PIN = 1; //analog pin used to connect the sensor
int ledPin = 9;  //select pin for the servo
int val = 0;  //variable to read the value from the analog pin
int adc_to_cm(int adc) {
  return 14251 * pow(adc,-1.17);
}

void setup()
{
  myservo1.attach(9); //set up the servo as usual first servo
    pinMode(ledPin, OUTPUT);  //variable to store the value coming from the sensor
  Serial.begin(9600);
}

void loop() {
  
  int reading = analogRead(SHARP_IR_PIN); // replace this pin with the analog pin your sensor is connected to
  int distance = adc_to_cm(reading);

  char buf[50];
  sprintf(buf, "Distance: %d, voltage: %.02f, adc: %d\r\n", distance, reading * 5.00 / 1024 , reading);
  Serial.print(buf);
  
  if (distance < 40) {
    myservo1.write(0);
    while (1);
          } 
      else {
    myservo1.write(180);
    delay(1500);
    }
    
}