Timer.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @file
  3. * @author Marek Bel
  4. */
  5. #include "Timer.h"
  6. #include "system_timer.h"
  7. /**
  8. * @brief construct Timer
  9. *
  10. * It is guaranteed, that construction is equivalent with zeroing all members.
  11. * This property can be exploited in menu_data.
  12. */
  13. template<typename T>
  14. Timer<T>::Timer() : m_isRunning(false), m_started()
  15. {
  16. }
  17. /**
  18. * @brief Start timer
  19. */
  20. template<typename T>
  21. void Timer<T>::start()
  22. {
  23. m_started = _millis();
  24. m_isRunning = true;
  25. }
  26. /**
  27. * @brief Timer has expired
  28. *
  29. * Timer is considered expired after msPeriod has passed from time the timer was started.
  30. * Timer is stopped after expiration.
  31. * This function must be called at least each (T maximum value - msPeriod) milliseconds to be sure to
  32. * catch first expiration.
  33. * This function is expected to handle wrap around of time register well.
  34. *
  35. * @param msPeriod Time interval in milliseconds. Do not omit "ul" when using constant literal with LongTimer.
  36. * @retval true Timer has expired
  37. * @retval false Timer not expired yet, or is not running, or time window in which is timer considered expired passed.
  38. */
  39. template<typename T>
  40. bool Timer<T>::expired(T msPeriod)
  41. {
  42. if (!m_isRunning) return false;
  43. bool expired = false;
  44. const T now = _millis();
  45. if (m_started <= m_started + msPeriod)
  46. {
  47. if ((now >= m_started + msPeriod) || (now < m_started))
  48. {
  49. expired = true;
  50. }
  51. }
  52. else
  53. {
  54. if ((now >= m_started + msPeriod) && (now < m_started))
  55. {
  56. expired = true;
  57. }
  58. }
  59. if (expired) m_isRunning = false;
  60. return expired;
  61. }
  62. /**
  63. * @brief Ticks since the timer was started
  64. *
  65. * This function returns 0 if the timer is not started. Otherwise, it returns
  66. * the time in milliseconds since the timer was started.
  67. * This function is expected to handle wrap around of time register well.
  68. * The maximum elapsed time is dictated by the template type
  69. */
  70. template<typename T>
  71. T Timer<T>::elapsed() {
  72. return m_isRunning ? (_millis() - m_started) : 0;
  73. }
  74. template<typename T>
  75. bool Timer<T>::expired_cont(T msPeriod)
  76. {
  77. return !m_isRunning || expired(msPeriod);
  78. }
  79. template class Timer<unsigned long>;
  80. template class Timer<unsigned short>;