From 3b0088f6e9c533ab045b6b82246cef4081331c4f Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 11 Mar 2017 00:49:36 +0700 Subject: [PATCH] implement delay_ns with DWT --- cores/nRF5/delay.c | 14 ++++++++++++++ cores/nRF5/delay.h | 30 +++++++++++++++++++++++++++++- cores/nRF5/nrf52_flash.c | 3 +++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/cores/nRF5/delay.c b/cores/nRF5/delay.c index 62cd6f27..e9fd16b8 100644 --- a/cores/nRF5/delay.c +++ b/cores/nRF5/delay.c @@ -40,6 +40,20 @@ void delay( uint32_t ms ) vTaskDelay(ms2tick(ms)); } +void dwt_enable(void) +{ + CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; /* Global Enable for DWT */ + DWT->CYCCNT = 0; /* Reset the counter */ + DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; /* Enable cycle counter */ +} + +void dwt_disable(void) +{ + DWT->CTRL &= ~DWT_CTRL_CYCCNTENA_Msk; + CoreDebug->DEMCR &= ~CoreDebug_DEMCR_TRCENA_Msk; +} + + #ifdef __cplusplus } #endif diff --git a/cores/nRF5/delay.h b/cores/nRF5/delay.h index 659b13c4..59e90774 100644 --- a/cores/nRF5/delay.h +++ b/cores/nRF5/delay.h @@ -56,7 +56,7 @@ extern uint32_t micros( void ) ; * * \param dwMs the number of milliseconds to pause (uint32_t) */ -extern void delay( uint32_t dwMs ) ; +extern void delay( uint32_t dwMs ); /** * \brief Pauses the program for the amount of time (in microseconds) specified as parameter. @@ -74,6 +74,34 @@ static __inline__ void delayMicroseconds( uint32_t usec ) nrf_delay_us(usec); } +void dwt_enable(void); +void dwt_disable(void); + + +/** + * Delay nano seconds, delay_ns() make use of DWT of debug core. + * dwt_enable() must be called previously. + * Note: nrf52 run at 64MHz + * - 1000 ns ~ 64 cycles + * - 500 ns ~ 32 cycles + * - 250 ns ~ 16 cycles + * - 125 ns ~ 8 cycles + */ +// Enable pragma when this bug is fixed https://bugs.launchpad.net/gcc-arm-embedded/+bug/1534360 +// #pragma GCC push_options +// #pragma GCC optimize ("Ofast") + +#define DELAY_CYCLE_CORRECTION 8 // ~125 ns overhead for delay_ns() +#define delay_ns(ns) \ + do {\ + register uint32_t _endtime = DWT->CYCCNT;\ + _endtime += ((F_CPU/1000000)*ns)/1000 - DELAY_CYCLE_CORRECTION;\ + while (DWT->CYCCNT < _endtime) {}\ + } while(0) + +// #pragma GCC pop_options + + #ifdef __cplusplus } #endif diff --git a/cores/nRF5/nrf52_flash.c b/cores/nRF5/nrf52_flash.c index 000a0d4e..0989bd8f 100644 --- a/cores/nRF5/nrf52_flash.c +++ b/cores/nRF5/nrf52_flash.c @@ -40,6 +40,7 @@ #if CFG_DEBUG #define CFG_DEBUG_NFFS 0 +#if CFG_DEBUG_NFFS static void print_buf(const uint8_t* address, uint32_t count) { for(uint32_t i=0; i