GD32F3x0 单片机使用定时器做Delay延时函数的代码:
#define USE_DELAY_TIMER 1
#if(USE_DELAY_TIMER)
#include "gd32f3x0_timer.h"
#define DELAY_TIMER TIMER13
#define RCU_DELAY_TIMER RCU_TIMER13
#define DELAY_TIMER_IRQHandler TIMER13_IRQHandler
#define DELAY_TIMER_IRQn TIMER13_IRQn
#define DELAY_TIMER_PRESCALER 0
#define DELAY_TIMER_PERIOD (SystemCoreClock / 1000 /1000)-1
#define TMR_ENABLE() TIMER_CTL0(DELAY_TIMER)|=(uint32_t)TIMER_CTL0_CEN
#define TMR_DISABEL() TIMER_CTL0(DELAY_TIMER) &= ~(uint32_t)TIMER_CTL0_CEN
#define TMR_CLR_FLAG() TIMER_INTF(DELAY_TIMER) = (~(uint32_t)TIMER_INT_FLAG_UP)
#define TMR_SET_CNT(X) TIMER_CNT(DELAY_TIMER) = (uint32_t)(X)
u16 us_count;
void Delay_Timer_Init(void)
{
timer_parameter_struct tmr;
rcu_periph_clock_enable(RCU_DELAY_TIMER);
timer_deinit(DELAY_TIMER);
tmr.prescaler = DELAY_TIMER_PRESCALER;
tmr.alignedmode = TIMER_COUNTER_EDGE;
tmr.counterdirection = TIMER_COUNTER_UP;
tmr.period = DELAY_TIMER_PERIOD;
tmr.clockdivision = TIMER_CKDIV_DIV1;
tmr.repetitioncounter = 0;
timer_init(DELAY_TIMER,&tmr);
timer_interrupt_enable(DELAY_TIMER,TIMER_INT_UP);
nvic_irq_enable(DELAY_TIMER_IRQn,2,0);
TMR_DISABEL();
}
void DELAY_TIMER_IRQHandler(void)
{
TMR_CLR_FLAG();
us_count++;
}
void Delay_1us(uint16_t count)
{
TMR_SET_CNT(0);
TMR_ENABLE();
us_count = 0;
while (us_count < count);
TMR_DISABEL();
}
void Delay_1ms(uint16_t count)
{
while (count--)
{
Delay_1us(1000);
}
}
#if(0)
void Test_Delay(void)
{
#define CNT 1000
while (1)
{
LED_SYS_ON();
delay_us(CNT);
LED_SYS_OFF();
delay_us(CNT);
LED_SYS_ON();
delay_us(CNT);
LED_SYS_OFF();
delay_us(CNT);
LED_SYS_ON();
delay_us(CNT);
LED_SYS_OFF();
delay_us(CNT);
}
}
#endif
#endif
|