It happens to almost everyone in robotics: you build a nice obstacle-avoiding robot. Code is ready, wiring is ready. You leave it in an empty corridor. It rolls happily, then suddenly brakes hard even though nothing is in front.
You stare in surprise while the robot acts like it hit an invisible wall. It did not go crazy. It saw a ghost. The technical name is sensor noise.
The problem: a filterless, too-trusting approach
An ultrasonic sensor sometimes produces a bad sample. Dust, air flow, or an echo can make a real 200 cm distance look like 5 cm for a moment.
In code we often trust one reading blindly:
if (distance < 10) {
stopNow();
}
The robot panics on that false 5 cm and stops. There is no obstacle; only a measurement error, noise.
The tip: filter with averaging
In real life we do not trust one claim instantly. If someone says it is 50 degrees outside, you do not remove your coat at once; you check again. Give the robot the same habit. That is called filtering. The simplest effective method is averaging.
A smart robot does not decide from one sample. In a few milliseconds it takes 5–10 readings in a row. Example:
200, 200, 5, 202, 198
That single bad 5 cm disappears among good values. The average stays close to the real distance. The robot stops for real obstacles, not ghosts.
int averageDistance() {
long sum = 0;
int n = 5;
for (int i = 0; i < n; i++) {
sum += readDistance();
delayMicroseconds(2000); // tiny gap, not a long sleep
}
return (int)(sum / n);
}
void loop() {
int distance = averageDistance();
if (distance > 0 && distance < 10) {
stopNow();
} else {
goForward();
}
}
Workshop note: Leave a very short gap between samples. This micro-wait is not the same trap as a long
delay(1000)that freezes the whole loop. You can also build the same idea withmillis().
Summary
A good robot programmer does not believe every sensor value instantly. Filter the data with math and stop only for real obstacles. Do not make a ghost hunter; teach the robot to analyze readings.