用systick实现ms级的延时没问题,但uS级的就比较麻烦。毕竟不建议随便改tick的分频
那么,如果是Corecm3内核的话,推荐这个:
uint32_t DWT_Delay_Init(void) {
/* Disable TRC */
CoreDebug->DEMCR &= ~CoreDebug_DEMCR_TRCENA_Msk; // ~0x01000000;
/* Enable TRC */
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; // 0x01000000;
/* Disable clock cycle counter */
DWT->CTRL &= ~DWT_CTRL_CYCCNTENA_Msk; //~0x00000001;
/* Enable clock cycle counter */
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; //0x00000001;
/* Reset the clock cycle counter value */
DWT->CYCCNT = 0;
/* 3 NO OPERATION instructions */
__ASM volatile ("NOP");
__ASM volatile ("NOP");
__ASM volatile ("NOP");
/* Check if clock cycle counter has started */
if(DWT->CYCCNT){
return 0; /*clock cycle counter started*/
} else {
return 1; /*clock cycle counter not started*/
}
}
__STATIC_INLINE void DWT_Delay_us(volatile uint32_t microseconds)
{
uint32_t clk_cycle_start = DWT->CYCCNT;
/* Go to number of cycles for system */
microseconds *= (HAL_RCC_GetHCLKFreq() / 1000000); //改变这个值,可以调整时间粒子
/* Delay till end */
while ((DWT->CYCCNT - clk_cycle_start) < microseconds);
}