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);
}