Naguissa / uTimerLib

Arduino tiny and cross-device compatible timer library
https://www.foroelectro.net/electronica-digital-microcontroladores-f8/utimerlib-libreria-arduino-para-eventos-temporizad-t191.html
GNU Lesser General Public License v3.0
20 stars 9 forks source link

SAMD21 Timing Incorrect #5

Closed svlPanelMaker closed 5 years ago

svlPanelMaker commented 5 years ago

Thanks for all your work in creating this library. It saved me a lot of time in figuring out how to do a simple timed interrupt on a SAMD21 (MKR 1010 to be specific).

However, in my checks I found that the timing provided by the setInterval_us command was off and actually running very slowly. My application initially required a 1000us interrupt and I found (via micros()) that I could only get 21845 us. In fact, it didn’t matter what value I passed in below 21845, I’d only got 21845! So upon further review of the code (and some trial and error), I’ve come to the conclusion that you need to reset the COUNT register to 0 on every interrupt. (In practice I made the change to only the _loadRemainder() routine and in the case where both _remainder and _overflows are 0 but I think just always reseting would work. And not changing both locations does leave timing errors). With both locations fixed, I now have micros() reporting desired timing to around 3 microseconds from 1000 microseconds to 1000000 micros = 1 sec. I did not review the other prescaler value/setInterval routine but I can only assume that the code is the same so it has the same issue.

(As an aside, I think you can get your code even smaller. Instead of running two different interrupt types, you could run OVF all the time and load COUNT = (_overflows > 0 ? 0 : (65535 - _remainder + 1)) assuming the counter is counting up. You might need a flag to tell the interrupt handler whether the remainder portion or overflow portion was running when the OVF occurred so that you can reload the _overflows and _remainder variables but it seems a bit simpler in general to me. I don't think this would change timing but I also haven't tried this method either.)

Cheers!

Naguissa commented 5 years ago

Thanks! I'll check that suggested changes and do a new release.

Naguissa commented 5 years ago

Fixed! https://github.com/Naguissa/uTimerLib/releases/tag/1.1.1

Thanks.

The second part is not implemented by now, as I think I did it for ESP8266 special case.