Arduino working delay function

I recently started actually playing with my arduino a bit more and got to a point where I needed to monitor user input on the device during a delay.

As I understand it, the delay() function stops the microcontroller in its tracks and all it does is count the interval specified (e.g. delay(1000) denotes 1000ms). The arduino playground provides a great example which I tweaked so it all sat in a function and could essentially replace all the delay function calls.

I used code from: http://arduino.cc/en/Tutorial/BlinkWithoutDelay as a basis and wrapped the key bits up in a function which you should just be able to copy and paste and replace all your delay calls with this function but of course remove the random number sum code as that’s just an example.

// Used instead of delay so various things can still be checked (e.g. button presses, saving data).
int workingDelay(int interval) {
  unsigned long previousMillis = millis();
  while (true) {
    unsigned long currentMillis = millis();
    Serial.println(currentMillis);
    // If the current miliseconds run is more than the interval, the delay has been done, so exit.
    if (currentMillis - previousMillis > interval) {
      return 0;
    } else {
      // running during delay
      int randNum1 = random(300);
      int randNum2 = random(300);
      int randNumSum = randNum1 + randNum2;
      Serial.println("Sum result:");
      Serial.println(randNumSum);
      // end running during delay
    }
  }
}

There is of course one thing to bear in mind which is that if you put a function that say takes 3 seconds in and use the delay button specifying an interval of 1 second, it’s just not going to work.

,

Leave a Reply

Your email address will not be published. Required fields are marked *