Ultrasonic sensor after filter periodic gives 1

I gust connect ultrasonic sensor with default sketch. With data, all is ok.(No random numbers in Serial)
After that I gust connect an output filter to send in Serial Port data only one ultrasonic data was changed it start to make noises in output. I don't know why.

#define LED_PIN  0 // D3
#define LED_PIN2 2 // D4

#define trigPin  5 // D1
#define echoPin  4 // D2

int distance;
int last_distance;
long duration;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(LED_PIN2, OUTPUT);
  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 * 0.034 / 2;

  if(last_distance - distance){ //filtre
    Serial.println(distance);
    last_distance = distance;   //filtre reset
  }
}

output

00:43:48.072 -> 7
00:43:48.072 -> 1
00:43:48.106 -> 7
00:43:48.106 -> 1
00:43:48.106 -> 7
00:43:48.106 -> 2
00:43:48.106 -> 7
00:43:48.106 -> 2
00:43:48.106 -> 7
00:43:48.106 -> 1
00:43:48.106 -> 7
00:43:48.106 -> 1

Welcome to the forum

As your question does not relate to the operation of IDE 1.x it has been moved to the Programming category of the forum

Explain better and show an image of this part.

That is new concept to me. Just what is it you are calling an "output filter" and where do you put it? Are you trying to filter noise from the echo sensor?

yeah, I change it to

if(last_distance != distance){

To send data on Serial only when data was changed, but it's still make mistakes. Like:
17:20:13.400 -> 7
17:20:13.400 -> 2
17:20:13.400 -> 7
17:20:13.400 -> 2
17:20:13.400 -> 7
17:20:13.400 -> 1

In comparison, if I delete just this "IF", the output data will be:
17:21:46.925 -> 7
17:21:46.925 -> 7
17:21:46.925 -> 7
17:21:46.925 -> 7
17:21:46.925 -> 7
17:21:46.925 -> 7
17:21:46.925 -> 7

Use serial plotter.

No, it is doing exactly what you want. It is only sending data if it changed.
What are you expecting to see?
Also you should have a delay(50) at the end of loop

Gust:
noun. a sudden, strong blast of wind

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.