Ultrasonic sensor with relay

Hey guys, I am am trying to make a code which automatically controls relay on basis of ultrasonic sensor measurements. I am using a nodeMCU as a microcontroller rather than an arduino. The relay and the ultrasonic sensor is being powered from a 5V source and nodemcu from a 3.3V Source. I don't think none of the sensors are interfering with each other as all the sensors are kept at a distance. Due to the random values my relay is being latched without any reason. Can someone please help me out with the problem. I don't want these values(above 3000) being shown in the serial monitor. Also please suggest me a better ultrasonic sensor than the HC-SR04.
Thanks

#define TRIGGER 5
#define ECHO    4
#define RELAY   0

void setup() {
  Serial.begin(9600);
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);
  pinMode(RELAY, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  }else{  
    digitalWrite(RELAY, LOW);
  }

  Serial.print("Centimeters: ");
  Serial.println(distance);

}

Hi,
Look up, google , Arduino Newping library.

It will make your code simpler and more compact when using the ultrasonic sensor.

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks.. Tom... :slight_smile:

@shubham1520

Other post/duplicate DELETED
Please do NOT cross post / duplicate as it wastes peoples time and efforts to have more than one post for a single topic.

Continued cross posting could result in a time out from the forum.

Could you also take a few moments to Learn How To Use The Forum.

Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.

Hey Tom
I am using nodemcu with ultrasonic sensor and newping library is only available for Arduino

Hi,

I don't think none of the sensors are interfering with each other as all the sensors are kept at a distance.

I only see one sensor connected to the MCU, what do you mean by interfering with each other?

Tom... :slight_smile:

Put a delay (50) at the bottom of loop().
Report back.

Also please suggest me a better ultrasonic sensor than the HC-SR04.

Please define “better”

I think it is premature to discuss replacing the ultrasonic sensor considering OP has not done anything to
the current circuit and software to correct the issue.
There's an example sketch in the library that displays range in cm on an LCD. I found it to be stable.