使用下面的stopwatch_delay(ticks)来完成延迟.它使用STM32的DWT_CYCCNT寄存器,该寄存器专门用于计算位于地址0xE0001004的实际时钟周期.
要验证延迟准确性(请参阅main),您可以调用STOPWATCH_START,运行stopwatch_delay(ticks),然后调用STOPWATCH_STOP并使用CalcNanosecondsFromStopwatch(m_nStart,m_nStop)进行验证.根据需要调整刻度.
uint32_t m_nStart; //DEBUG Stopwatch start cycle counter value
uint32_t m_nStop; //DEBUG Stopwatch stop cycle counter value
#define DEMCR_TRCENA 0x01000000
/* Core Debug registers */
#define DEMCR (*((volatile uint32_t *)0xE000EDFC))
#define DWT_CTRL (*(volatile uint32_t *)0xe0001000)
#define CYCCNTENA (1<<0)
#define DWT_CYCCNT ((volatile uint32_t *)0xE0001004)
#define CPU_CYCLES *DWT_CYCCNT
#define STOPWATCH_START { m_nStart = *((volatile unsigned int *)0xE0001004);}
#define STOPWATCH_STOP { m_nStop = *((volatile unsigned int *)0xE0001004);}
static inline void stopwatch_reset(void)
{
/*