Hi, I’m having a problem envolving arduino’s (both uno and due) timer and a software timer I made.
I made this code to isolate the problem:
#include <TimerOne.h>
typedef uint32_t mod_timer_t;
/*
************************************************************************************************************************
Software Timer implementation. It works like this: When I instantiate an STimer,
I set its period on the constructor call. There is this static_timer_count which is
incremented each timer interruption. When I start a implementation of STimer,
the object will save (in offset variable) the current value of static_timer_count.
When I call check(), the difference between static_timer_count and offset is compared
to period, If its bigger or equal, true is returned, otherwise, false is returned.
************************************************************************************************************************
*/
class STimer
{
public:
static mod_timer_t static_timer_count;
mod_timer_t period = 1; //in ms
mod_timer_t offset = 0;
bool working = false;
STimer(mod_timer_t period){ //period in milisseconds
this->period = period;
}
void reset(){
working = true;
offset = static_timer_count;
}
bool check(){ // tells if the timer reached its period
if(working){
if((mod_timer_t)(static_timer_count - offset) >= period){
offset = static_timer_count;
return true;
}
}
return false;
}
};
// static_timer_count initialization.
mod_timer_t STimer::static_timer_count = 0;
//STimer implementation.
STimer alarm(1000);
// holds led position, HIGH or LOW.
bool led_position = false;
// similar to led position
bool togg = false;
void isr_timer(){
STimer::static_timer_count++;
// this is for check on osciloscope. Its working.
togg ^= 1;
digitalWrite(12, togg);
}
void setup(){
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
Timer1.initialize(1000);
Timer1.attachInterrupt(isr_timer);
alarm.reset();
}
void loop(){
// this while holds the execution until alarm set off.
while(!(alarm.check()));
// when alarm sets off, the led_position is inverted and the led shall blink.
led_position ^= 1;
digitalWrite(13, led_position);
alarm.reset();
}
This code doesn’t work. The strange part is that if I change this loop for this, It works!!
void loop(){
if(alarm.check()){
led_position ^= 1;
digitalWrite(13, led_position);
alarm.reset();
}
}
Any Ideas of what could make this happen? Just to remember, I tested this with both Uno and Due timers.