Software Timer stops working

Hi all,

So im trying the following code. The idea is just to turn on a led when an external interrupt appears (which im simulating with a button fro now), and then automatically turn it off using a timer, After i press the button a few times, the led turns on but never goes off again. So i guess the timer stops working.

Any ideas?

Thanks :smile:

SYSTEM_THREAD(ENABLED)

int out = 3;
int in = 2;

Timer counter1(20, sendSignal);

void sendSignal(){
    digitalWrite(D7, LOW);
    counter1.stop();
}

void zero_cross(void);


void setup() {
    pinMode(D7, OUTPUT);
    digitalWrite(D7, LOW);
    pinMode(D2, INPUT_PULLDOWN);
    attachInterrupt(D2, zero_cross, RISING);
}

void loop() {
}

void zero_cross(){
    counter1.start();
    digitalWrite(D7, HIGH);
}

@alexgrauer, since you starting the timer from the ISR, you need to use counter1.startFromISR() instead of the regular start command as per the documentation. :wink:

3 Likes

BTW, there is also the option for a one-shot timer (in the same docs), so no need to call counter1.stop()

2 Likes

Thanks both for the quick response.
I changed the code but still same thing happens! :frowning:

@alexgrauer, what is the rate of zero_cross interrupts? If it is, as I assume, 50Hz, this would explain the 20ms timer. However, the software timer has a 1ms jitter, meaning it takes up to 1ms to start or stop since the minimum resolution is 1ms. It could be that the calling `counter1.startFromISR() in zero_cross() is re-triggering the timer before it gets a chance to expire. This would give the appearance that the counter is not working.

2 Likes

@alexgrauer have you been able to fix this issue yet? Let us know if there is anything else we can do to help you.

Thanks @peekay123 and @ScruffR for providing your thoughts :slight_smile: