Incredible readings - HC-SR04

Hello I'm beginner with Arduino and found a problem which I cannot to solve or find any constructable answer. I use ultrasonic sensor HC-SR04 for measure distance. The readings are done by a series of commands:

digitalWrite(trigPin, LOW); delayMicroseconds(5); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);

The sensor works, generally reads correct data but every few correct reading I achieve completely silly values, for example: 27 27 26 27 27 26 26 26 26 25 25 25 26 26 27 3266 19 3262 19 112 3230 19 3268 19 119 3247 19 3229 21 25 26

and then it reads real distance (object placed at approx. 25 cm) These huge values it gives sometimes in a series as above and sometimes only one for few seconds. I tried to filter power supply of the sensor (100uF and 100nF), tried to change the off state before read digitalWrite(trigPin, LOW); delayMicroseconds(n); n from 2 to 20 but it didn't help. Do you know what is the reason of this problem? Thanks in advance!

All sensors will occasionally give false readings.

Your code must be able to discard obviously wrong values. There are various approaches, like averaging several measurements (possibly discarding outliers).


The newping library can give you averaged results.

Example code I know works is HERE

See newping info HERE

See "Timer Median "