I am trying to set an LED on pin 8 to turn on only when the Ultrasonic sensor sees at a certain distance, but the LED is always on. here is the code
const int TrigPin = 2;
const int EchoPin = 3;
const int ledpin1 = 8;
float cm;
void setup()
{
Serial.begin(9600);
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
pinMode(ledpin1, OUTPUT);
}
void loop()
{
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
cm = pulseIn(EchoPin, HIGH) / 58.0; //The echo time is converted into cm
cm = (int(cm * 100.0)) / 100.0; //Keep two decimal places
Serial.print("Distance\t=\t");
Serial.print(cm);
Serial.print("cm");
Serial.println();
if(cm > 20) {
digitalWrite(ledpin1, HIGH);
}else if(cm < 20){
digitalWrite(ledpin1, HIGH);
}
delay(1000);
}
Any help would be appreciated!