Set a timer for a function

Hi everyone,

I will try as best as I can to explain what I want to do. I have got a 4 x 4 matrix keypad where is used for password insertion. I want to apply a restriction for the user.. The user will have a certain period of time (that I will set) to insert the password. After the passing of the set time the user wouldn't be able to insert the password anymore.

In other words what I want to do is a function that will be active for x seconds of time (where the user wIll be able to insert the password)

Any advice would be helpfull

Here’s a simple way to run something for x amount of time.

const unsigned long interval = 10000; // 10 secs

void function() {
  unsigned long currentMillis = millis();
  unsigned long timeout = currentMillis + interval;
  while (currentMillis < timeout) {
     // run some code for 10 seconds
     currentMillis = millis();

Thanks KawasakiZx10r!!

I never used again millis(). Great to know about that!!

When does the timer start? My guess it that it starts when the first key is pressed. That would look something like this:

unsigned long Timertart = 0;
const unsigned long MAX_TIME = 30000;
byte EnteredDigitCount = 0;
unsigned long EnteredValue = 0;

void ResetDigitEntry()
  EnteredValue = 0;
  EnteredDigitCount = 0;
  TimerStart = 0;

void loop()
  int key = keypad.getKey();

  switch (key)
    case NO_KEY: break;

    case '0'..'9':
      if (TimerStart == 0)
        TimerStart = millis();
      EnteredValue *= 10;
      EnteredValue += key - '0';

    case ENTER:
      if (EnteredValue == PASSCODE_VALUE && EnteredDigitCount == PASSCODE_DIGIT_COUNT)
        // UNLOOCKED
        // UNLOOCK failed

    case CLEAR:

  if (TimerStart != 0 && millis() - TimerStart >= MAX_TIME)
    // Data entry has timed out


Hi johnwasser,

Indeed, the timer starts when the * key is pressed. Thank you for your assistant!!!

Is there any difference whether the "ResetDigitEntry" function is before of after the void loop?

You know, there's a whole forum dedicated to introductory tutorials. It's called Introductory Tutorials. There are some great posts in there that really should be read to help you understand basic Arduino.

That's a great section, I didn't know about that!!

Thank you DKWatson

Nikosant03: Is there any difference whether the "ResetDigitEntry" function is before of after the void loop?

In Arduino programming it should not make a difference. In traditional C and C++ programing a function has to be declared somewhere above the function where it is called. If, for style reasons, you wanted to declare the body of the function below where the function is called you have to put a "function prototype" above the function that does the call. In this case the prototype would be "void ResetDigitEntry();". The Arduino IDE tries to protect you from that C/C++ requirement by generating prototype for each your functions at the top of the sketch. Most times it works. :)