Why does my Arduino script do the opposite of what I want?

Hey out there! I am trying to write a code for an Arduino project I am working on. I am using an ultrasonic proximity sensor and an arduino nano clone. What I want is that when the object it detects is under 50cm an led turns on. When it senses an object farther than 50cm I want theLED to go off. Below is the script I wrote. The problem is it does the opposite of what I want(objects >50 LED goes on, objects <50 LED goes off). Any help would be greatly appreciated! Thanks!



#define trigPin 3
#define echoPin 9
int LED = 12;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  float duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
 
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;
 
  if (distance >= 50){
    Serial.print("Distance = ");
    Serial.println("Out of range");
    digitalWrite(LED, LOW);
  }
  else {
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.println(" cm");
    digitalWrite(LED, HIGH);
    delay(500);
  }
  delay(500);
}


iceng1 month ago

Could the led be wrongly tied to the other gnd-to-Vcc or Vcc-to-Gnd..

iceng iceng1 month ago

Look at A & B, the output pin is HIGH but only ON with ckt A..

Look at D & C, the output pin is Low but only Off with ckt D..

Click the pic to view the whole image..

uP-LED.bmp
Mpc1055 (author)  iceng1 month ago

That's it, THANKS!!!!!!!!!

rickharris1 month ago

Your prog does just what you told it to do:

" if (distance >= 50){ IF the distance (I guess this is the same as object in your question), is greater or equal to 50 then LED Off.
Serial.print("Distance = ");
Serial.println("Out of range");
digitalWrite(LED, LOW);
}
else {
Serial.print("Distance = ");
Serial.print(distance);
Serial.println(" cm");
digitalWrite(LED, HIGH);
delay(500);"

Swap >= for <=

and swap <= for >= further down.