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