#include "Bsp.h"

#define  DEM_CR      *(volatile u32 *)0xE000EDFC
#define  DWT_CR      *(volatile u32 *)0xE0001000
#define  DWT_CYCCNT  *(volatile u32 *)0xE0001004

#define  DEM_CR_TRCENA                   (1 << 24)
#define  DWT_CR_CYCCNTENA                (1 <<  0)

/**
 * @brief  初始化延时函数
 * @param  void
 * @retval void
 * @note   void
 * @example void
 */
void DelayConfig(void)
{
    DEM_CR  |=  DEM_CR_TRCENA; 
    DWT_CR  |=  DWT_CR_CYCCNTENA;
    DWT_CYCCNT = 0;
}

/**
 * @brief  读取DWT计数器的值
 * @param  void
 * @retval void
 * @note   void
 * @example void
 */
unsigned int DwtCntGet(void)
{
    return((uint32_t)DWT_CYCCNT);
}

/**
 * @brief  微秒级延时函数
 * @param  void
 * @retval void
 * @note   void
 * @example void
 */
void DelayUs(unsigned int Us)
{
     uint32_t Start = 0,End = 0,Ts = 0;
     Start = DwtCntGet();
 
     Ts =  Us * (SystemCoreClock / 1000000U);      
 
     End = Start + Ts;      
 
     while(DwtCntGet() < End){;}
}
/**
 * @brief  毫秒级延时函数
 * @param  void
 * @retval void
 * @note   void
 * @example void
 */
void DelayMs(unsigned int Ms)
{
    DelayUs(Ms * 1000);
}
