Timer.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @file
  3. * @author Marek Bel
  4. */
  5. #include "Timer.h"
  6. #include "Arduino.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 MenuData union.
  12. */
  13. Timer::Timer() : m_isRunning(false), m_started()
  14. {
  15. }
  16. /**
  17. * @brief Start timer
  18. */
  19. void Timer::start()
  20. {
  21. m_started = millis();
  22. m_isRunning = true;
  23. }
  24. /**
  25. * @brief Timer has expired
  26. *
  27. * Timer is considered expired after msPeriod has passed from time the timer was started.
  28. * This function must be called at least each (unsigned long maximum value - msPeriod) milliseconds to be sure to
  29. * catch first expiration.
  30. * This function is expected to handle wrap around of time register well.
  31. *
  32. * @param msPeriod Time interval in milliseconds.
  33. * @retval true Timer has expired
  34. * @retval false Timer not expired yet, or is not running, or time window in which is timer considered expired passed.
  35. */
  36. bool Timer::expired(unsigned long msPeriod)
  37. {
  38. if (!m_isRunning) return false;
  39. bool expired = false;
  40. const unsigned long now = millis();
  41. if (m_started <= m_started + msPeriod)
  42. {
  43. if ((now >= m_started + msPeriod) || (now < m_started))
  44. {
  45. expired = true;
  46. }
  47. }
  48. else
  49. {
  50. if ((now >= m_started + msPeriod) && (now < m_started))
  51. {
  52. expired = true;
  53. }
  54. }
  55. if (expired) m_isRunning = false;
  56. return expired;
  57. }