Timer.cpp 1.3 KB

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