title: Distance controlled led
body: <p>I'm trying to create a distance controlled LED that turns off at a certain distance. I'm using an arduino Leonardo and a distance sensor. At the moment when I plug in my board the led stays on permanently and doesn't turn off when the distance reduces. Please can you tell me what needs changing in order for this to work?</p>
  
  <pre><code>const int TrigPin = 2;
  const int EchoPin = 3;
  float cm;
  int ledPin = 12; //define ledPin12 is the output port of led’s level.
  int val = 0; //define original of val.
  void setup() 
  {
      Serial.begin(9600);
      pinMode(TrigPin, OUTPUT);
      pinMode(EchoPin, INPUT);
      pinMode(ledPin, OUTPUT); //set ledPin output
  }
  void loop()
  {
      digitalWrite(TrigPin, LOW); //Low-high-low level sent a short time pulse to TrigPin
      delayMicroseconds(2);
      digitalWrite(TrigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(TrigPin, LOW);
      cm = pulseIn(EchoPin, HIGH) / 58.0; //Echo time converted into cm
      cm = (int(cm * 100.0)) / 100.0; // retain two decimal places
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();
      delay(1000);
  
      val = analogRead(EchoPin); //get the value from sensor
      if(val&lt;=1)
      {
          //512=2.5V, if want the sensor be more sensitive, increase the number, or lese low the number.
          digitalWrite(ledPin, HIGH); //when the value of val is less than 512(2.5V), light up led lamp
      }
      else
      {
          digitalWrite(ledPin, LOW);
      }
  }
  </code></pre>