Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

setPeriod() starts new period with whatever is left over in TCNT1 #18

Open
samcarson opened this issue Sep 28, 2016 · 7 comments
Open

Comments

@samcarson
Copy link

If a stop() is issued for a running timer, TCNT1 is not cleared and a subsequent setPeriod() will start with the residual initial value.
The following will reproduce the problem

timer1.initialize(3000000); //start a three second timer
delay(2000); //wait 2 seconds
timer1.stop(); //stop timer1
// TCNT1 contains the residual
unsigned long saveStartTime = millis();
timer1.setPeriod(2000000); // set new 2 second timer
TIFR1 = _BV(TOV1); // Be sure overflow flag is cleared
while(!(TIFR1 & TOV1)); // wait for timer overflow
Serial.print("Timer expired at ");
Serial.print(millis() - saveStartTime);
Serial.println(" milliseconds);

Note: the expire interval can be ANY value BUT IT WILL NOT BE 2000 MILLISECONDS!! This is a consequence of the calculation of the prescaler bits.

@samcarson
Copy link
Author

Leave a comment

1 similar comment
@samcarson
Copy link
Author

Leave a comment

@samcarson
Copy link
Author

Correction:
Timer1 overflow test should be
while(!(TIFR1 & _BV(TOV1))); // wait for timer overflow

@samcarson
Copy link
Author

Further testing results:

If the timer was counting down when stopped, it will continue counting down after a setPeriod() thus setting the overflow when the residual TCNT1 count goes to 0. Thus the first interval after the setperiod() is incorrect. This probably does not matter for PWM but is critical it using the timer for timeout intervals, for example looking for a response from a device within a specific time after a command .

@RossAWaddell
Copy link

samcarson - did you ever get a workaround for this? I think this is exactly the problem I'm seeing with my project where I want to restart the count if a button is pushed, but it doesn't seem to work with the simple stop() and start() functions (or even using setperiod(x)). In my case, I initialize Timer1 with a period of 5 seconds in setup() but then use stop() so it doesn't start the compare until a button is pushed. I got this working but the second part is if the user pushes a 2nd button before the 5 secs it should restart from the beginning, but it doesn't.

@samcarson
Copy link
Author

samcarson commented Apr 8, 2019 via email

@samcarson
Copy link
Author

samcarson commented Apr 8, 2019 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants