diff delay.c @ 40:a38003b97de6

Use debug cycle counter to handle delays.
author Daniel O'Connor <darius@dons.net.au>
date Mon, 01 Apr 2013 20:06:03 +1030
parents 891841f5f785
children cecb0506f4b8
line wrap: on
line diff
--- a/delay.c	Mon Apr 01 19:45:38 2013 +1030
+++ b/delay.c	Mon Apr 01 20:06:03 2013 +1030
@@ -1,83 +1,36 @@
+#include <assert.h>
 #include <stdint.h>
 #include "stm32f10x.h"
 #include "delay.h"
 
 /* Sleep for nCount usec
- * TDS1012 on 2.5usec/div shows...
- *   30usec = 29.60usec 
- *   60usec = 59.20usec 
- *
- * XXX: not sure disable IRQ stuff is working as I see occasional (small) extra delays
  */
 void
 delay(uint32_t nCount) {
-    __disable_irq();
-    for(; nCount != 0; nCount--) {
-#ifdef SYSCLK_FREQ_72MHz
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
+    uint32_t dly, cnt, clk_per_usec, max_dly;
+    volatile uint32_t *DWT_CYCCNT = (uint32_t *)0xe0001004;
 
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
+    __disable_irq();
 
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
-	__asm__("nop");
+#ifdef SYSCLK_FREQ_72MHz
+    clk_per_usec = 72;
+    max_dly = (1<<31) / clk_per_usec; /* Really half the maximum (still ~30 seconds at 72MHz) */
 #else
-#error Unknown clock frequency
+#error "Unknown clock frequency"
 #endif
-    }
+    assert(nCount < max_dly);
+    
+    cnt = *DWT_CYCCNT; /* Get current cycle count */
+    dly = nCount * clk_per_usec;
+    dly += cnt; /* Compute cycle count to stop at */
+    if (dly < cnt)
+	/* Stop count wrapped, wait until the counter wraps around */
+	while (*DWT_CYCCNT > cnt)
+	    ;
+    /* Wait until we get to the stop count */
+    while (*DWT_CYCCNT < dly)
+	;
+    
     __enable_irq();
 }