timer.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <ch.h>
  2. #include "timer.h"
  3. static uint32_t reset_point = 0;
  4. #if CH_CFG_ST_RESOLUTION < 32
  5. static uint32_t last_systime = 0;
  6. static uint32_t overflow = 0;
  7. #endif
  8. void timer_init(void) { timer_clear(); }
  9. void timer_clear(void) {
  10. reset_point = (uint32_t)chVTGetSystemTime();
  11. #if CH_CFG_ST_RESOLUTION < 32
  12. last_systime = reset_point;
  13. overflow = 0;
  14. #endif
  15. }
  16. uint16_t timer_read(void) { return (uint16_t)timer_read32(); }
  17. uint32_t timer_read32(void) {
  18. uint32_t systime = (uint32_t)chVTGetSystemTime();
  19. #if CH_CFG_ST_RESOLUTION < 32
  20. // If/when we need to support 64-bit chips, this may need to be modified to match the native bit-ness of the MCU.
  21. // At this point, the only SysTick resolution allowed other than 32 is 16 bit.
  22. // In the 16-bit case, at:
  23. // - CH_CFG_ST_FREQUENCY = 100000, overflow will occur every ~0.65 seconds
  24. // - CH_CFG_ST_FREQUENCY = 10000, overflow will occur every ~6.5 seconds
  25. // - CH_CFG_ST_FREQUENCY = 1000, overflow will occur every ~65 seconds
  26. // With this implementation, as long as we ensure a timer read happens at least once during the overflow period, timing should be accurate.
  27. if (systime < last_systime) {
  28. overflow += ((uint32_t)1) << CH_CFG_ST_RESOLUTION;
  29. }
  30. last_systime = systime;
  31. return (uint32_t)TIME_I2MS(systime - reset_point + overflow);
  32. #else
  33. return (uint32_t)TIME_I2MS(systime - reset_point);
  34. #endif
  35. }
  36. uint16_t timer_elapsed(uint16_t last) { return TIMER_DIFF_16(timer_read(), last); }
  37. uint32_t timer_elapsed32(uint32_t last) { return TIMER_DIFF_32(timer_read32(), last); }