Line data Source code
1 : #pragma once 2 : 3 : #include <AH/Settings/NamespaceSettings.hpp> 4 : 5 : #include <AH/Arduino-Wrapper.h> // millis, micros 6 : 7 : BEGIN_AH_NAMESPACE 8 : 9 : /// @addtogroup AH_Timing 10 : /// @{ 11 : 12 : /// A function type that returns a time value. 13 : using timefunction = unsigned long (*)(); 14 : 15 : /** 16 : * @brief A class for easily managing timed events. A wrapper for "Blink 17 : * Without Delay". 18 : * 19 : * @tparam time 20 : * The time function to use. 21 : */ 22 : template <timefunction time = micros> 23 : class Timer { 24 : public: 25 : /** 26 : * @brief Constructor. 27 : * @param interval 28 : * The interval between two events. 29 : */ 30 2 : Timer(unsigned long interval) : interval(interval) { 31 : #ifdef ARDUINO 32 : begin(); 33 : #endif 34 2 : } 35 : /// Initialize or reset the timer. The timer will fire immediately. 36 2 : void begin() { previous = time() - interval; } 37 : /// Initialize or reset the timer. The timer will fire after one period. 38 : void beginNextPeriod() { previous = time(); } 39 : /// Update the timer and return true if the event should fire. 40 20 : explicit operator bool() { 41 20 : auto now = time(); 42 20 : if (now - previous >= interval) { 43 8 : previous += interval; 44 8 : return true; 45 : } 46 12 : return false; 47 : } 48 : 49 : /// Get the interval of the timer. 50 : unsigned long getInterval() const { return interval; } 51 : /// Set the interval of the timer. 52 : void setInterval(unsigned long interval) { this->interval = interval; } 53 : 54 : private: 55 : unsigned long interval; 56 : unsigned long previous = 0; 57 : }; 58 : 59 : /// @} 60 : 61 : END_AH_NAMESPACE