使用定时器代替Systick延时,不使用中断,不改变原子的接口

时间:2023-01-22 23:37:03

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 
static u32 fac_us=0;    //us延时倍乘数

void delay_init(u8 SYSCLK)
{
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;     

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14, ENABLE); 
    
    TIM_TimeBaseStructure.TIM_Period = 65535-1;    
    TIM_TimeBaseStructure.TIM_Prescaler = 1-1;  
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; 
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1 ;
    TIM_TimeBaseInit(TIM14, &TIM_TimeBaseStructure);
    
    fac_us = SYSCLK;

    TIM_SetCounter(TIM14,0);
    TIM_Cmd(TIM14, ENABLE); 
    
}

 
void delay_us(u32 nus)
{       
    u32 ticks;
    u32 told,tnow,tcnt=0;
    u32 reload=65535-1;             
    ticks=nus*fac_us;               
    told=TIM14->CNT;                
    while(1)
    {
        tnow=TIM14->CNT; 
        if(tnow!=told)
        {       
            if(tnow>told)tcnt+=tnow-told;   
            else tcnt+=reload-told+tnow;    
            told=tnow;
            if(tcnt>=ticks)break;           
        }  
    };
}


void delay_ms(u32 nms)
{
    u32 i;
    for(i=0;i<nms;i++) delay_us(1000);
}