Advertisement
Krzyspx

timers.h

Jun 5th, 2016
6,086
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include "Arduino.h"
  2.  
  3. #ifndef timers_h
  4. #define timers_h
  5.  
  6. typedef void (*timerFunc)(void);
  7. typedef void (*timerEventFunc)(byte);
  8.  
  9. void nullTimerFunc(void)
  10. {
  11.   return;
  12. }
  13.  
  14. void nullOnTimeFunc(byte element)
  15. {
  16.   return;
  17. }
  18.  
  19. struct TimerElement
  20. {
  21.   timerFunc func;
  22.   unsigned long interval;
  23.   unsigned long begin_time;
  24. };
  25.  
  26.  
  27. template<byte TIMER_ITEMS>
  28. class Timers
  29. {
  30.   private:
  31.     struct TimerElement _elements[TIMER_ITEMS];
  32.    
  33.   public:
  34.     timerEventFunc onTime;
  35.  
  36.     Timers(void)
  37.     {
  38.       for (int i=0; i<TIMER_ITEMS; i++)
  39.       {
  40.         _elements[i].func = nullTimerFunc;
  41.         _elements[i].interval = 0;
  42.         _elements[i].begin_time = 0;
  43.       }
  44.  
  45.       onTime = nullOnTimeFunc;
  46.     }
  47.  
  48.     void attach(byte element, unsigned long interval, timerFunc func)
  49.     {
  50.       _elements[element].func = func;
  51.       _elements[element].interval = interval;
  52.       _elements[element].begin_time = millis();
  53.     }
  54.  
  55.     void setInterval(byte element, unsigned long interval)
  56.     {
  57.       _elements[element].interval = interval;
  58.       _elements[element].begin_time = millis();
  59.     }
  60.  
  61.     void updateInterval(byte element, unsigned long interval)
  62.     {
  63.       _elements[element].interval = interval;
  64.     }
  65.  
  66.     void process(void)
  67.     {
  68.       unsigned long actual_time = millis();
  69.      
  70.       for (int i=0; i<TIMER_ITEMS; i++)
  71.       {
  72.         long long delta_time = actual_time - _elements[i].begin_time;
  73.        
  74.         if (delta_time < 0)
  75.         {
  76.           delta_time += 0xffffffff;
  77.           delta_time += 1;
  78.         }
  79.         if (_elements[i].interval > 0 && delta_time >= _elements[i].interval)
  80.         {
  81.           onTime(i);
  82.           _elements[i].func();
  83.           _elements[i].begin_time = actual_time;
  84.         }
  85.       }
  86.     }
  87. };
  88.  
  89. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement