use tick counter for delay. this seems to work but can't guarantee
authorDarron Broad <darron@kewl.org>
Thu, 19 Mar 2015 18:02:35 +0000
changeset 2 6094fff1c533
parent 1 84a5087bc52e
child 3 f66e5c3fc87f
use tick counter for delay. this seems to work but can't guarantee
it's reliable. needs more testing.
miniblink.c
mk/Makefile.rules
--- a/miniblink.c	Wed Mar 18 22:11:14 2015 +0000
+++ b/miniblink.c	Thu Mar 19 18:02:35 2015 +0000
@@ -19,11 +19,46 @@
 
 #include <libopencm3/stm32/rcc.h>
 #include <libopencm3/stm32/gpio.h>
+#include <libopencm3/cm3/nvic.h>
+#include <libopencm3/cm3/systick.h>
+
+static volatile uint32_t ticktock = 0;
+
+void sys_tick_handler(void)
+{
+	if (ticktock)
+		ticktock--;
+}
+
+static void clock_setup(void)
+{
+	rcc_clock_setup_in_hse_8mhz_out_72mhz();
+
+	/* 72MHz / 8 => 9000000 counts per second */
+	systick_set_clocksource(STK_CSR_CLKSOURCE_AHB_DIV8);
+
+	/* 9000000/9000 = 1000 overflows per second - every 1ms one interrupt */
+	/* SysTick interrupt every N clock pulses: set reload to N-1 */
+	systick_set_reload(8999);
+
+	systick_interrupt_enable();
+}
+
+static void delay_ms(uint32_t ms)
+{
+	ticktock = ms;
+
+	/* Start counting. */
+	systick_counter_enable();
+
+	while (ticktock)
+		;
+
+	systick_counter_disable();
+}
 
 static void gpio_setup(void)
 {
-	rcc_clock_setup_in_hse_8mhz_out_72mhz();
-
 	/* Enable GPIOB clock. */
 	rcc_periph_clock_enable(RCC_GPIOB);
 
@@ -34,13 +69,14 @@
 
 int main(void)
 {
+	clock_setup();
+
 	gpio_setup();
 
 	/* Blink the LED (PB1) on the board. */
 	while (1) {
 		gpio_toggle(GPIOB, GPIO1);	/* LED on/off */
-		for (int i = 0; i < 0x400000; i++)	/* Wait a bit. */
-			__asm__("nop");
+		delay_ms(1000);
 	}
 
 	return 0;
--- a/mk/Makefile.rules	Wed Mar 18 22:11:14 2015 +0000
+++ b/mk/Makefile.rules	Thu Mar 19 18:02:35 2015 +0000
@@ -20,10 +20,10 @@
 ##
 
 # Be silent per default, but 'make V=1' will show all compiler calls.
-ifneq ($(V),1)
-Q		:= @
-NULL		:= 2>/dev/null
-endif
+#ifneq ($(V),1)
+#Q		:= @
+#NULL		:= 2>/dev/null
+#endif
 
 ###############################################################################
 # Executables