Ultrasonic HC-SR04 faulty

Hi guys,

I am using an HC-SR04 with an Arduino Uno as a sensor.

Gnd=5
Echo=4
Trigg=3
Vcc=2

I have written a programme which turns on a succession on LEDs based on proximity.

My only issue is sporadic readings... When I view the serial monitor the readings as a Serial.println, tend to settle on one distance BUT random numbers seem to pop in.

Here is an extract from my code:

if (cm<20){
digitalWrite(redLed,HIGH);
delay(200);

}

else if (cm<50){
digitalWrite(greenLed,HIGH);
delay(200);
}

As you can see my condition is distance, and hence random readings popping up mean that my other LEDs will sporadically illuminate when they shouldn't.

Any advice anyone has would be greatly appreciated!

Many thanks in advance,

Will

you need to convert the readings to cm before you use them for anything else. the readings directly from the sensor are the duration it took for the ultrasonic wave it senses.
try this instead.

/*
HC-SR04 Ping distance sensor
VCC to Arduino 5V
GND to Arduino GND
Echo to Arduino pin 13
Trig to Arduino pin 12
*/

#define trigPin 12
#define echoPin 13

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if (distance >= 400 || distance <= 2){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

You might also want to use a running average to filter out the noise.