can someone help me with my code?

hello again! I’m trying to write a program that makes a LED light if the distance (read from a PING ultrasonic sensor is less than a X distance but have a servo sweep if the distance is more than X however, when I run the program the PING ultrasonic doesn’t turn on and the servo only “jiggles”. I have already checked to see If it is a hardware problem by running some sample code on it. Please help -GeckoLink

#include <Servo.h>
Servo myservo;

const int pingPin = 7;

int pos = 0;
int LEDpin = 8;
void setup() {
  
  Serial.begin(9600);
  myservo.attach(9);
  pinMode(LEDpin, OUTPUT);
}

void loop()
{
  
  long duration, inches, cm;

 
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

 
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

 
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
 
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
 
   
   if(inches <= 10)
  {
  for(pos = 0; pos < 90; pos += 1);
  }
  {
    myservo.write(pos);
    delay(15);
  }
  for(pos = 90; pos>=1; pos-=1)
  {                                
    myservo.write(pos); 'pos';
    delay(15);
    
    if(inches >= 10)
    digitalWrite(LEDpin, HIGH);
    delay(10000);
    digitalWrite(LEDpin, LOW);
    
  }
 
  delay(100);
}

long microsecondsToInches(long microseconds)
{
  
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  
  return microseconds / 29 / 2;
}
if(inches <= 10)
  {
  for(pos = 0; pos < 90; pos += 1);
  }
  {

That for loop isn’t doing anything very useful.

I was wondering: the code with pingPin in loop(), is that to turn the ping on?

If so, then you are calling it repeatedly in the loop(), which means it is called as fast as possible - with your delay at the bottom of loop(), that means about 10 times a second or so.

It might also make coding easier for you to break it up into two parts - first get the code working for the range detection, then get the code wondering for the servo movement, then combine them.

As suggested above, you may want to create separate functions to handle the sensor and the servo.

Here is some pseudo code, you would need to move your current code into these new functions:

void loop()
{
   int distance = getDistance(); // a method that contains the ping code
  //print distance 
  if distance > 10)
  {
     sweepServo(); // a method to swing the servo from side to side
  }
}

then get the code wondering for the servo movement

I've often thought that's how people wrote code for servos.