Ultrasonic Sensor(HC-SR04) recording random distance
These random values could be nothing but noise as your receiver may be sensing other source of ultra sound. In your case, the circuit is especially sensitive as the output powers a relay and any noise in the input side will cause the relay to &quot;chatter&quot;. There are many approaches to filtering and smoothing out the signal. One method would be to implement a basic averaging algorithm where you take several readings and then average out the result. Compare this result with the threshold and the output should be smoother.
EDIT
Here is a rudimentry example, where I take multiple readings (nb_measurements measurements) and then take the average over it:
long getDuration() {
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

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

  digitalWrite(TRIGGER, LOW);
  return pulseIn(ECHO, HIGH);
}

void loop() {
  float duration = 0, distance = 0;
  int nb_measurements = 10;
  for (int i = 0; i &lt; nb_measurements; i++) {
    duration += getDuration();
  }
  duration = duration/nb_measurements;
  distance = (duration / 2) / 29.1;

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

  Serial.print(&quot;Centimeters: &quot;);
  Serial.println(distance);

}

Due to the extra processing, this will be in theory slower than your previous code but in practice, you wouldn't perceive it as long as you keep nb_measurements at a reasonable value. There are more complex digital signal filtering algorithms, search around and you can find good documentation and libraries online.