\
\ 	timing functions with Systick-Timer
\
\		Ralph Sahli, 2016
\		
\		resources used:
\			- system timer
\	

0 variable tick#							\ tick counter of 1 ms ticks

\ get MHz from hclk
: mhz@ ( -- MHz )
	hclk @ 1000000 / ;
	
: systimer-irq-handler
	1 tick# +! ;

: init-Systimer ( -- )
    0 $E000E010 ! 							\ Disable SysTick during setup
	hclk @ 1000 / 							\ 1 ms @ HCLK
    1- $E000E014 !	    					\ reload value for 24 bit timer
    0 $E000E018 !							\ Any write to current clears it
	['] systimer-irq-handler irq-systick !  \ Hook for handler
	%111 $E000E010 !	;					\ AHB-clock, interrupt enabled, counter enabled

: millis ( -- msCount )
	tick# @ inline ;

: start-timer ( ms -- endTime )
	$E000E010 @ 0= if init-Systimer then	\ initialize if not done
	millis + ;

: elapsed-ms ( startTime -- startTime ms ) 
	millis over - inline ;

: elapsed? ( endTime -- endTime flag )
	pause elapsed-ms 0 >= ;

: delay-ms ( ms -- )
	start-timer 
	begin
		elapsed? 
	until drop ;
