COSA
An Object-Oriented Platform for Arduino Programming
Watchdog.cpp
Go to the documentation of this file.
1 
21 #include "Cosa/Watchdog.hh"
22 #include "Cosa/Math.hh"
23 #include "Cosa/Power.hh"
24 #include "Cosa/Bits.h"
25 
26 // Initated flag
27 bool Watchdog::s_initiated = false;
28 
29 // Milli-seconds counter and number of ms per tick
30 uint32_t Watchdog::s_millis = 0L;
31 uint16_t Watchdog::s_ms_per_tick = 16;
32 
33 // Watchdog Job Scheduler (milli-seconds level delayed functions)
34 Watchdog::Scheduler* Watchdog::s_scheduler = NULL;
35 
36 // Watchdog Alarm Clock (seconds level delayed functions)
37 Watchdog::Clock* Watchdog::s_clock = NULL;
38 
39 uint8_t
40 Watchdog::as_prescale(uint16_t ms)
41 {
42  // Map milli-seconds to watchdog prescale values
43  uint8_t prescale = log2<uint16_t>((ms + 8) >> 5);
44  if (UNLIKELY(prescale > 9)) prescale = 9;
45  return (prescale);
46 }
47 
48 void
49 Watchdog::begin(uint16_t ms)
50 {
51  // Map milli-seconds to watchdog prescale values
52  uint8_t prescale = as_prescale(ms);
53 
54  // Create new watchdog configuration
55  uint8_t config = _BV(WDIE) | (prescale & 0x07);
56  if (prescale > 0x07) config |= _BV(WDP3);
57 
58  // Update the watchdog registers
59  synchronized {
60  wdt_reset();
61  bit_clear(MCUSR, WDRF);
62  WDTCSR = _BV(WDCE) | _BV(WDE);
63  WDTCSR = config;
64  }
65 
66  // Mark as initiated and set watchdog delay as global delay
67  s_ms_per_tick = (1 << (prescale + 4));
69  s_initiated = true;
70 }
71 
72 void
73 Watchdog::delay(uint32_t ms)
74 {
75  uint32_t start = Watchdog::millis();
76  ms += s_ms_per_tick / 2;
77  while (since(start) < ms) yield();
78 }
79 
81 {
82  // Increment milli-seconds counter
83  Watchdog::s_millis += Watchdog::s_ms_per_tick;
84 
85  // Run all expired jobs
86  if (Watchdog::s_scheduler != NULL)
87  Watchdog::s_scheduler->dispatch();
88 
89  // Increment the clock and run expired alarms
90  if (Watchdog::s_clock != NULL)
91  Watchdog::s_clock->tick(Watchdog::s_ms_per_tick);
92 }
static uint32_t millis()
Definition: Watchdog.hh:51
#define NULL
Definition: Types.h:101
static uint32_t since(uint32_t start)
Definition: Watchdog.hh:108
friend void WDT_vect(void)
#define bit_clear(p, b)
Definition: Bits.h:36
static void begin(uint16_t ms=16)
Definition: Watchdog.cpp:49
void(* yield)()
#define WDTCSR
Definition: ATtinyX5.hh:231
void tick(uint16_t ms)
Definition: Clock.hh:94
ISR(WDT_vect)
Definition: Watchdog.cpp:80
#define UNLIKELY(x)
Definition: Types.h:153
virtual void dispatch()
static void delay(uint32_t ms)
Definition: Watchdog.cpp:73