Ultrasonic sensor showing incorrect reading(HCSR-04)

Hi,

I am using ultrasonic sensor HCSR-04 it is interfaced with nodemcu.

My problem : Incorrect reading if the distance is 10cm at first it shows 10cm without changing the distance it show 2cm or 3cm or 0cm.

I cant find a solution plz help me?

code :

int trigPin = D0; //Trig
int echoPin = D1; //Echo
long duration, cm;

void setup() {
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop()
{

// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.

duration = pulseIn(echoPin, HIGH);

// convert the time into a distance

cm = duration*0.034/2;

Serial.print(cm);
Serial.println("/n");

delay(2000);
}

Is that a 5V or 3.3V HC-SR04? Most are 5V but 3.3V versions do exist. For your NodeMCU you must have one that's rated to work at 3.3V or you may get odd effects.

Make cm a float type instead of a long type. Makes more sense here. You can use byte type for your pin numbers, and save some memory.

What happens with larger distances?

ya its a 5v ultrasonic sensor i am not using the nodemcu supply(3.3v) i am taking the power from a raspberry pi 3.

Are the grounds connected?

It's a bad idea to send 5V signals to the NodeMCU as the pins are not 5V tolerant!

Now I happened to have seen the schematic of the HC-SR04 just the other day in another thread, and in this sensor the 5V output signal is done using a pull-up resistor so that's what keeps your NodeMCU alive. Most 5V sensors have driven high outputs which would kill your input pins by overloading them.

ya ground is connected