Hi,
I am using an Arduino Uno and I want to be able to dynamically create timers.
I don't want to use the delay-function mainly because I want to understand how timers works and also I need to react to some user input buttons.
I found a library called Timer1 which seems to be the way to go.
Basically in the loop-function I want to react to some user input and activate a motor either going backward or forward and then stop the motor after a certain period of time (lets say 5 seconds).
I create a timer when the motor is started and then wait for the interrupt to be called so I can turn the motor off.
Below is my code: (I removed most of the unnecessary code)
You know, you can create a timer class that you can start() and then in your loop() ask if it's expired(). Being a class you can create as many different ones as you want. (This is what I do.)
There is a potential problem with the timer.start() function. It is noted in the Timer 1 library comments.
The overflow interrupt gets triggered when TCNT1 is reset to 0.
From the TimerOne library code
//****************************
// Run Control
//****************************
void start() __attribute__((always_inline)) {
TCCR1B = 0;
TCNT1 = 0; // TODO: does this cause an undesired interrupt?
resume();
}
void stop() __attribute__((always_inline)) {
TCCR1B = _BV(WGM13);
}
void restart() __attribute__((always_inline)) {
start();
}
void resume() __attribute__((always_inline)) {
TCCR1B = _BV(WGM13) | clockSelectBits;
}
There is a work around which sets TCNT1 =1. You can modify the library code.
I was also surprised to find out that you can actually leave the library alone, and change the sketch. I don't quite understand why it works, but I think that's because of the large prescaler used for the 5 second period so that you can increment TCNT1 before the timer actually starts and sets the interrupt.