Filter a sensor value using millis ()

Hello all,

I have a sketch for control a water pump. In order to start/stop the pump I am using an ultrasonic sensor connected to Arduino. I have a problem reading the ultrasonic sensor value, because sometimes a value spike is triggered and this causes the pump to start. I would like to implement a loop using millis () function in order to start the pump only if the sensor value is greater than the set point for 10 seconds.
Some advice please ?
Thanks in advance

Post your sketch.

Yes, please post the sketch.

Often beginning designers stumble on this common problem, until it is re-conceptualized:

"Do X if Y is true for more than Z seconds"
"Do X if the last time Y was false, is more than Z seconds before now"

Using millis() for timing tutorials:
Several things at a time.
Beginner's guide to millis().
Blink without delay().

Hello, thanks all for your replies.
Below you can see my sketch. Right now I am using delay function to check if the tank level is greather than setpoint. But I would like to check if the tank level is greather than setpoint during 10 seconds. If yes, I will start the pump. If not I will not start the pump.


#define DHTTYPE DHT11      // DHT 11
#define dht_dpin 2
#include <BlynkSimpleShieldEsp8266.h>
#include "DHT.h"
#include "SR04.h"
#define TRIG_PIN 12
#define ECHO_PIN 11

// Declare the variables
SR04 sr04 = SR04(ECHO_PIN, TRIG_PIN);//Sensor ultrasonidos
long distancia, nivel, nivelSP = 60;
const int PINLT1  = 2, PINLT2  = 3, PINBOMBA  = 9;
DHT dht(dht_dpin, DHTTYPE);
SimpleTimer timer1, timer2, timer3;
int LT1 = HIGH;
boolean AnalogOn = false, DigitalOn = false;
unsigned long tiempoPrevioA = 0,tiempoPrevioD = 0;

  nivelSP = param.asInt(); // Get value as integer

void NivelDigital()
 LT1 = digitalRead(PINLT1);
 if (LT1 == LOW) //nivel alto detectado
      tiempoPrevioD = millis ();
      DigitalOn = true;
 if ((DigitalOn == true) and ((millis() - tiempoPrevioD) > 2700000))
      DigitalOn = false;

void NivelAnalogico()
 distancia = sr04.Distance();
 nivel = 130 - distancia; // nivel de agua en el pozo en centímetros
 if ((nivel < 30) and (AnalogOn == true) and((millis() - tiempoPrevioA) > 1800000))
      AnalogOn = false;
 if (nivel > nivelSP)
     delay (5000);
     distancia = sr04.Distance();
     nivel = 130 - distancia;
     if (nivel > nivelSP)
          AnalogOn = true;
          tiempoPrevioA = millis ();

void setup()
  digitalWrite(PINBOMBA , HIGH);
  // Debug console

  // Setup a function to be called every x second
  timer2.setInterval(2000, NivelDigital);
  timer3.setInterval(2000, NivelAnalogico);

  pinMode (PINLT1,INPUT); //switch de nivel LT1
  pinMode (PINLT2,INPUT); //switch de nivel LT2
  pinMode (PINBOMBA,OUTPUT); //orden bomba


void loop()

  if ((DigitalOn == true) or (AnalogOn == true))
      digitalWrite(PINBOMBA , LOW);
      digitalWrite(PINBOMBA , HIGH);