int sonarPin = 0; //connect to analog 0.

int ledPin = 13; // I used 13, because I am using an Uno, I dont have an APM free right now                 

                       // and I am lazy and do not feel like finding a resister and LED

int cm;             // XL sonar is calibrated to cm, more or less

int dist;  //if you do any calculations, see below


void setup() { 

  Serial.begin(9600); 

  pinMode(sonarPin, INPUT); // I think it is good practice to define this 

  pinMode(ledPin, OUTPUT); 

  delay(500);                        // wait for the serial to begin!

}


void loop() { 

  cm = analogRead(sonarPin); // you should really sample and take a mode/median value; do not average 

  // dist = analogRead(sonarPin)/2*(0.3937);

  /* I do not know where this formula comes from,

   * are you using XL? I have seen many formulas, x/1024.0/5000 / 9.8 * 2.54 is common,

   * or x * 1.??, but for cm, raw value works well for XL. 

   */

  Serial.print(cm); 

  Serial.println("cm");

  if(cm < 40) {

    // sensor min distance is ~20-22cm  

    Serial.println("cm < 40"); 

    digitalWrite(ledPin, HIGH);    

    delay(50);                   // WARNING: this will "block" your sonar speed when objects are near!

                                     // Change to 1000 to see more clearly.   

    digitalWrite(ledPin, LOW);   

    delay(50);                   // changed to "delay", and 50ms because "delayMicroseconds(500)" produces

                                     // too fast blinks, eye cannot see 

  }

}