Is millis need to reset ?

Go To Last Post
7 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

 

I use millis to count time for two hours. After two hours, I reset the timer count, shall I take opportunity to reset the millis_count to avoid millis go overrun ?

 

If yes, I try to reset millis this way, is it correct  ?

 

void reset_millis(){
	cli();//no interrupt
	millis_value = 0;//reset millis, is this correct ?
	sei();
	
}

Help is appreciated.  Thank you.

  

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Are you talking about "Arduino" or some other use of "millis" ?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

 

I use Timer0 as millis counter in C using Atmel Studio as below. 

 

unsigned long millis()
{
	unsigned long m;
	uint8_t oldSREG = SREG;
	// Disable interrupts while we read millis_value or we might get an
	// inconsistent value (e.g. in the middle of a write to millis_value)
	ATOMIC_BLOCK(ATOMIC_FORCEON){
			cli();
			m = millis_value;
			SREG = oldSREG;
	}
	return m;
}
ISR(TIMER0_COMPA_vect)
{
	// Increment millisecond every 1ms
	millis_value++;
}

 

So I am thinking of resetting the millis_value instead of letting it go keep running. 

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You don't need that at all.
Even if it keeps running for 100 years, it can count the time within 49 days infinitely accurately.
If something goes wrong, it's a bug in your code.
There are many explanations on the net.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

hamisu wrote:

So I am thinking of resetting the millis_value instead of letting it go keep running.

 

bool hasTimedOut(unsigned long timeNowMs,
                 unsigned long timeThatTimeOutWasStartedMs,
                 unsigned long timeOutPeriodMs)
{
  return (timeNowMs - timeThatTimeOutWasStartedMs) >= timeOutPeriodMs;
}

The above code will work even when millis_value rolls over .

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

 

Thank you all for the confirmation.  

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

hamisu wrote:

ATOMIC_BLOCK(ATOMIC_FORCEON){

This is generally a bad idea since it means you can't call millis() when interrupts are disabled (well, you can, but interrupts will unexpectedly be re-enabled after the call to millis()). I'd use ATOMIC_RESTORESTATE here.

Last Edited: Wed. Sep 21, 2022 - 05:16 PM