Timer.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @file
  3. * @author Marek Bel
  4. */
  5. #include "Timer.h"
  6. #include "Marlin.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. template class Timer<unsigned long>;
  63. template class Timer<unsigned short>;