0
int tPin = 11;
int ePin = 12;
long duration, inches, cm;

void setup()
{
    Serial.begin(9600);
    pinMode(tPin, OUTPUT);
    pinMode(ePin, INPUT);
    pinMode(2, OUTPUT);
}

void loop()
{
    digitalWrite(tPin, LOW);
    delayMicroseconds(5);
    digitalWrite(tPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(tPin, LOW);
    duration = pulseIn(ePin, HIGH);
    cm = (duration / 2) / 29.1;
    inches = (duration / 2) / 74;
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if (inches <= 10) {
        digitalWrite(2, HIGH);
        delay(50);
        digitalWrite(2, LOW);
        delay(50);
    }
    else {
        digitalWrite(2, HIGH);
        delay(500);
        digitalWrite(2, LOW);
        delay(500);
    }
}

The serial print displays the same distance that it first detects. How can I fix this?

  • 2
    What number does it constantly output? Also be aware that you do integer divisions when you do / 2 and / 74, you should change them to float values and also make cm and inches float. – Maximilian Gerhardt May 11 at 12:20
  • Are you sure it detects the same distance? How far did you try to move the object from the sensor? – AnT May 12 at 13:58
1

First of all you need to make cm, inches and duration float to be more precise. Second, you need to make the delay 2 and 10 microseconds between triggers. Overall, if I'm not wrong you can use the code below without changing your circuit.

int tPin = 11;
int ePin = 12;
float duration, inches, cm; //floating numbers to make the result more precise

void setup()
{
    Serial.begin(9600);
    pinMode(tPin, OUTPUT);
    pinMode(ePin, INPUT);
    pinMode(2, OUTPUT);
}

void loop()
{
    digitalWrite(tPin, LOW);
    delayMicroseconds(2);         //Delay 2 microseconds
    digitalWrite(tPin, HIGH);
    delayMicroseconds(10);        //Delay 10 microseconds
    digitalWrite(tPin, LOW);
    duration = pulseIn(ePin, HIGH);
    cm = duration / 58.2;          //Instead of duration/2/28.1
    inches = cm / 2.54;            //You can use cm that was created before for conversion
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if (inches <= 10) {
        digitalWrite(2, HIGH);
        delay(50);
        digitalWrite(2, LOW);
        delay(50);
    }
    else {
        digitalWrite(2, HIGH);
        delay(500);
        digitalWrite(2, LOW);
        delay(500);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.