1. 程式人生 > >stm32f103 time2配置,轉載

stm32f103 time2配置,轉載

//----------------------------main()--------------------

//stm32f103c8t6有3個普通1個高階定時器
//每次進入中斷服務程式間隔時間為
//((1+TIM_Prescaler )/72M)*(1+TIM_Period )=((1+7199)/72M)*(1+9999)=1秒
#include<stm32f10x.h>
#define D13_ON GPIO_ResetBits(GPIOC,GPIO_Pin_13)
#define D13_OFF GPIO_SetBits(GPIOC,GPIO_Pin_13)

void GPIO_Config(void);
void TIM2_Config(u16 arr,u16 psc);
void NVIC_Config(void);

//主函式
int main(void)
{
    GPIO_Config();
    //((1+arr )/72M)*(1+psc )=((1+1999)/72M)*(1+35999)=1秒
    TIM2_Config(1999,35999);
    NVIC_Config();
    while(1);

}

//初始化GPIO
void GPIO_Config(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);

    //PC13燈
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOC,&GPIO_InitStructure);
    GPIO_ResetBits(GPIOC,GPIO_Pin_13); //關閉LED
}


//初始化TIM2定時器及中斷
//每次進入中斷服務程式間隔時間為
//((1+arr )/72M)*(1+psc )=((1+1999)/72M)*(1+35999)=1秒
void TIM2_Config(u16 arr,u16 psc)
{
    //定時器時間是1s

    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
    //清除中斷標誌位
    TIM_ClearITPendingBit(TIM2,TIM_IT_Update);//TIM_ClearFlag(TIM2,TIM_FLAG_Update);//兩者作用相同

    //自動裝載的週期值0-0xffff,72M/36000=2000
    TIM_TimeBaseStructure.TIM_Period = arr;
    //時鐘除數預分頻值0-oxffff,下面是36000分頻
    TIM_TimeBaseStructure.TIM_Prescaler = psc;
    ////普通和高階才有下面兩行
    //時鐘分割,暫時為0,高階應用才用
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    //計數模式,向上下,中央對齊123
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

    TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);

    //開啟中斷
    TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
    //開啟外設
    TIM_Cmd(TIM2,ENABLE);
}

//初始化中斷向量控制器NVIC

void NVIC_Config(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}



//--------------------stm32f10x_it.c------------------------
//中斷函式中自己編寫
void TIM2_IRQHandler(void)
{
    //判斷TIM3更新中斷是否發生
    if(TIM_GetITStatus(TIM2,TIM_IT_Update)!=RESET)
    {
        //必須清楚標誌位
    TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
    //狀態取反
    GPIO_WriteBit(GPIOC,GPIO_Pin_13,(BitAction)(!GPIO_ReadOutputDataBit(GPIOC,GPIO_Pin_13)));
    }

}
--------------------- 
作者:sea1216 
來源:CSDN 
原文:https://blog.csdn.net/sea1216/article/details/80621489 
版權宣告:本文為博主原創文章,轉載請附上博文連結!