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