How to blink the LED forever when detect an object is more than 30 cm away using ultrasonic sensor I would like to make an alarm system using ultrasonic sensor.

My aim is to blink an LED for ever once ultrasonic sensor detect an object is more than 30 cm away.

But the problem is that my code some time fail to detect object accurate distance and even LED blinks but when ultrasonic sensor off LED becomes off.

I am using timer to on the ultrasonic sensor for 2 minutes (timer code not attached) so within that period if it detect an object is more than 30 cm away it blinks the LED till the power is cut.

int echoPin = 10; // pin 10 for the echo 

int trigPin = 9; // pin 9 for trigger
int duration, inches, cm; // Establish variables for duration of the ping, and the distance result
#include &lt;NewPing.h&gt; // Library for improved ultrasonic sensor readings

#include &lt;SoftwareSerial.h&gt;

NewPing sonar(trigPin, echoPin,30); // sets up the sonar function and limits distance to 30 cm

int ledpin=7;
// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 250;           // interval at which to blink (milliseconds

void setup() {
    pinMode(ledpin,OUTPUT);
    Serial.begin(9600); //sets up serial monitor
}

void loop() {

    delay(50);

    Serial.print("Ping: ");
    Serial.print(sonar.ping_cm());
    Serial.println("cm");

    //warning
    Serial.println("cm");

    //warning
    if(sonar.ping_cm()&gt;=30)
    {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis &gt;= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledpin, ledState);
      }

    }
}
You are initiating the NewPing library with NewPing sonar(trigPin, echoPin,30);. The last parameter is the maximum distance in cm, that will be measured. On the Arduino Playground site of the library it says 


  sonar.ping_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit 


You're not handling the special case of no ping (in the defined limit), which occurs everytime you exceed 30cm in your case, and your value cannot get greater than 30 cm. You can change the if-statement for your warning from

if(sonar.ping_cm()&gt;=30)


to

if(sonar.ping_cm()==0)