Millis() doesn't count

I'm using millis() to do a time counter but as I print it only display number 5. I don't get it.

I used to use the function in else if loop and it works well but after I connected to the sensor it only display number 5.

#include <TM1637.h>
#include <TM1637Display.h>
#define CLK 8
#define DIO 9
unsigned long millisec = 0;
unsigned long sec = 0;
int zoneinput = 3; 
int inhiritoutput = 2;
int zonecheck; 
//int inpos
//int inposcheck;

TM1637 tm(CLK,DIO);

void setup() {

  pinMode(zoneinput, INPUT);
  pinMode(inhiritoutput, OUTPUT);
  sec = millis();
  millisec = millis(); 

void loop() {
  zonecheck = digitalRead(zoneinput); 

 if(zonecheck == 1) // haven't boat
  else if(zonecheck == 0) // dont forget 1 to0
    tm.display(3, millisec %10 );
    int pos2 = millisec / 10;
    tm.display(2, pos2 % 10);
    int pos1 = pos2 / 10;
    tm.display(1, pos1 % 10);
    int pos0 = pos1 / 10;
    tm.display(0, pos0 % 10);
  return 0;

If you are referring to the value in the variable millisec, then it never gets updated after setup().

you are not checking the millis() in your loop so it will not update you just set millisec to whatever it was when it passed it in setup. needs to be in loop

Ok i tried and it helped. But I want it to start count when the function is true. Do you have suggestion?

Which function?

void means that loop() does not return anything. So why would you return 0?

in else if loop

"else if" is not a loop. "for" and "while" are loops. "if else" executes the lines of code inside it once, but conditionally.

If you want to measure the total time that your sensor is triggered (or not triggered), you need to detect the moment the sensor becomes triggered and record the value of millis() at that moment. At the moment the sensor ceases to be triggered, you can calculate the time it was triggered for and add this to the total.

1 Like

Okay. Now I'm clarified with the millis() problem. Thank you Paul :smiley:

If close timing matters, use micros() instead of millis(). Millis() is a milli-bit 'funny'.

more question. How to detect and stored the millis value when the sensor is triggered?

Use an unsigned long variable.

1 Like
unsigned long markTime;  // default is zero

//........... and below, somewhere in loop or a function called by loop

    if ( digitalRead( irSensePin ) == HIGH ) 
        markTime = millis();  // in 1 second, millis() - markTime will be 1000
            // the end - start = elapsed formula works across rollover, 
            // never needs checking, max interval is > 49.71 days. 

Contact switches, buttons and like "bounce" on change. Debouncing involves time.

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