I am trying to filter ultrasonic readings using averaging technique. I've also used millis() to measure time from start so that I can calculate readings up to 1 second and average them. I've re-initialized the elapsedTime variable each time to zero in the loop but again when the program execution hits this code the time starts from the time it was before. Is there any way to solve this problem?

This is the code:

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

int dist, ctr, filteredDist;
long rawValue = 0;
unsigned long StartTime = millis();

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
void loop() {
  unsigned long elapsedTime = StartTime;

  while (elapsedTime < 1000) {
    dist = sonar.ping_cm();
    rawValue += dist;
    elapsedTime = millis();
  filteredDist = rawValue / ctr;
  • You're looking at absolute times (the time since boot). You need to look at time differences. That means performing subtraction.
    – Majenko
    Nov 12, 2017 at 13:57
  • @Majenko thanks for your reply. It would be great if you would slightly modify the code.
    – Arun Subba
    Nov 12, 2017 at 14:01
  • I can't "slightly" modify the code. It needs a complete rewrite. There's not a lot that can be salvaged there except the ping code.
    – Majenko
    Nov 12, 2017 at 14:41
  • Look at the BlinkWithoutDelay example, and consider using a library for the averaging - such as my Average library.
    – Majenko
    Nov 12, 2017 at 14:42

1 Answer 1


elapsedTime=millis(); sets elapsedTime equal to the current value of millis(), which in the sketch above is the total time since the Uno powered up. Thus elapsedTime will exceed 1000 any time after the first second of execution, in which case the while won't do anything.

Instead say elapsedTime=millis() - StartTime; within the loop. Whenever you want to start the averaging cycle again, say StartTime = millis();.

If your only use of elapsedTime is to control the while loop, get rid of that variable; instead of while(elapsedTime < 1000), say while(millis()-StartTime < 1000).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.