Search code examples
arduinopingled

How to turn on an LED on a certain distance with an Arduino


I'm making an Arduino program and I can't get it to work.

All the program does is turn an LED on whenever someones becomes 5 inches away from the sensor. The problem is whenever I start the program the LED stays off no matter what. Here's my program

const int pingPin =7 ;
const int ledPin = 13;

void setup() {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
}

void loop() {
    long duration, inches, cm;

    pinMode(pingPin,OUTPUT);
    digitalWrite(pingPin,LOW);
    delayMicroseconds(2);
    digitalWrite(pingPin,HIGH);
    delayMicroseconds(5);
    digitalWrite(pingPin,LOW);

    pinMode(pingPin,INPUT);
    duration =pulseIn(pingPin,HIGH);

    inches = microsecondsToInches(duration);
    cm = microsecondsToCentimeters(duration);

    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    while (true) {
        if (inches <= 5) {
            digitalWrite(ledPin, HIGH);
        }
        else {
            digitalWrite(ledPin, LOW);
        }
    }
}

long microsecondsToInches(long microseconds)
{
    return microseconds /74/2;
}

long microsecondsToCentimeters(long microseconds)
{
    return microseconds /29/2;
}

How can I fix this so that the LED turns on and off at the correct distances?


Solution

  • Take a close look at this last bit of your code:

    while (true) {
      if (inches <= 5) {
        digitalWrite(ledPin, HIGH);
      } else {
        digitalWrite(ledPin, LOW);
      }
    }
    

    You see what it is doing? It is looping forever.

    So... your var inches gets a value once and then for all and eternity (or until you unplug) that value will remain the same..

    Get rid of the while() and you should see some responsiveness (assuming everything else is hooked up correctly).