stm32f103 延时20ns,在STM32上生成C中的纳秒延迟
使用下面的stopwatch_delay(ticks)來完成延遲.它使用STM32的DWT_CYCCNT寄存器,該寄存器專門用于計(jì)算位于地址0xE0001004的實(shí)際時鐘周期.
要驗(yàn)證延遲準(zhǔn)確性(請參閱main),您可以調(diào)用STOPWATCH_START,運(yùn)行stopwatch_delay(ticks),然后調(diào)用STOPWATCH_STOP并使用CalcNanosecondsFromStopwatch(m_nStart,m_nStop)進(jìn)行驗(yàn)證.根據(jù)需要調(diào)整刻度.
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)
{
/* Enable DWT */
DEMCR |= DEMCR_TRCENA;
*DWT_CYCCNT = 0;
/* Enable CPU cycle counter */
DWT_CTRL |= CYCCNTENA;
}
static inline uint32_t stopwatch_getticks()
{
return CPU_CYCLES;
}
static inline void stopwatch_delay(uint32_t ticks)
{
uint32_t end_ticks = ticks + stopwatch_getticks();
while(1)
{
if (stopwatch_getticks() >= end_ticks)
break;
}
}
uint32_t CalcNanosecondsFromStopwatch(uint32_t nStart, uint32_t nStop)
{
uint32_t nDiffTicks;
uint32_t nClkTicksPerMicrosec;
nDiffTicks = nStop - nStart;
nDiffTicks *= 1000; // Scale diff by 1000.
nClkTicksPerMicrosec = SystemCoreClock / 1000000; // Convert (clkTicks/sec) to (clkTicks/microsec), SystemCoreClock = 168000000
return nDiffTicks / nClkTicksPerMicrosec; // nanosec = (ticks * 1000) / (clkTicks/microsec)
}
void main(void)
{
int timeDiff = 0;
stopwatch_reset();
STOPWATCH_START;
run_my_function();
STOPWATCH_STOP;
timeDiff = CalcNanosecondsFromStopwatch(m_nStart, m_nStop);
printf("My function took %d nanoseconds\n", timeDiff);
}
總結(jié)
以上是生活随笔為你收集整理的stm32f103 延时20ns,在STM32上生成C中的纳秒延迟的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python123第三单元测试卷_第三单
- 下一篇: 第一课 让人拍案叫绝的创意都是如何诞生的