Modified version of the Watchdog library with improved support for STM32

Dependents:   LightSaber iot_water_monitor_v2

Fork of Watchdog by David Smart

Revision:
7:8912bb017956
Parent:
5:2dad2a78ffbd
Child:
8:3c7d083f26b5
--- a/Watchdog.cpp	Mon Mar 16 01:04:32 2015 +0000
+++ b/Watchdog.cpp	Tue Oct 27 16:02:33 2015 +0000
@@ -75,12 +75,29 @@
     wdreset = (RCC->CSR & (1<<29)) ? true : false;  // read the IWDGRSTF (Independent WD, not the windows WD)
 }
 
+// Compute the log2 of an integer. This is the simplest algorithm but probably is a bit slow.
+int log2(unsigned v)
+{
+    unsigned r = 0;             
+    
+    while (v >>= 1)
+      r++;
+                          
+    return r;                        
+}
+
+
 /// Load timeout value in watchdog timer and enable
-void Watchdog::Configure(int pr) {
+void Watchdog::Configure(float s) {
     // http://www.st.com/web/en/resource/technical/document/reference_manual/CD00171190.pdf
+    
+    s = s * 40000;                  // The average frequency of STM32 watchdog timer is 40 kHz but it can vary between 30 and 60 kHz
+    int scale = 1 + log2(s / 4096); // The RLR register is 12 bits and beyond that a prescaler should be used
+    int residual = s / (1 << scale); // The value for the RLR register
+    
     IWDG->KR  = 0x5555;         // enable write to PR, RLR
-    IWDG->PR  = pr;             // Init prescaler, page 486 Reference Manual
-    IWDG->RLR = 0xFFF;          // Init RLR
+    IWDG->PR  = scale - 2;      // Prescaler has values of multiples of 4 (i.e. 2 ^2), page 486 Reference Manual
+    IWDG->RLR = residual;       // Init RLR
     IWDG->KR  = 0xAAAA;         // Reload the watchdog
     IWDG->KR  = 0xCCCC;         // Starts the WD
 }