Reputation: 101
I'm quite new to Arduino but I'm trying to learn but currently, I'm having an issue. The output when the sensor stationary shows distance spikes. Is it a faulty sensor or is there a problem in the code?
Output:
Distance: 3540.65
Distance: 25.93
Distance: 3528.96
Distance: 25.42
Distance: 3550.34
Distance: 25.88
Distance: 3536.78
Distance: 36.27
Distance: 3501.94
Distance: 25.42
Distance: 28.37
Distance: 3531.37
Distance: 24.51
Distance: 26.99
Code:
* HC-SR04 example sketch
*
* https://create.arduino.cc/projecthub/Isaac100/getting-started-with-the- hc-sr04-ultrasonic-sensor-036380
*
* by Isaac100
*/
const int trigPin = 9;
const int echoPin = 10;
float duration, distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration*.0343)/2;
Serial.print("Distance: ");
Serial.println(distance);
delay(100);
}
Upvotes: 1
Views: 885
Reputation: 69
I think that you found answer to your question, but in future I would recommend you to filter those values. Maybe think about simple median filter or low pass filter.
Median filter:
Take last X(may be 5 for example) values and put them into an array.
Sort the array. Get the array[(X/2)] value. Now its a bit more usefull.
You may dynamically add data so you dont have to accumulate 10 of them and then filter it. For example if you receive new measurement A:
A - new measurement value
X - amount of data to accumulate (filter strength)
0 <= i < X
array[X] - array with accumulated data
array[i] = A;
i++;
if(i==X) i=0;
Simple as that.
Upvotes: 1