STM32学习笔记——基础定时器

程序运行结果:LED灯周期性闪烁

代码:
main.c:

#include "stm32f10x.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_tim.h"
#include "misc.h"

void RCC_Configuration(void);
void GPIO_Configuration(void);
void NVIC_Configuration(void);
void TIM_Configuration(void);

int main(void)
{
    RCC_Configuration();
    GPIO_Configuration();
    NVIC_Configuration();
    TIM_Configuration();
    while(1);
}

void RCC_Configuration(void)
{
    SystemInit();
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM7, ENABLE);//TIM2~7属于APB1
}

void GPIO_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOD, &GPIO_InitStructure);
}

void NVIC_Configuration(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
    NVIC_InitStructure.NVIC_IRQChannel = TIM7_IRQn;//设置中断线
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

void TIM_Configuration(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

    TIM_DeInit(TIM7);
    TIM_TimeBaseStructure.TIM_Prescaler = 36000-1;//定义预分频数值,此时定时器输入时钟频率=APB1时钟/(预分频数组+1)=72MHz/36000=2000Hz,即定时器每秒钟计数2000次
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_Period = 1000;//定时器预装载值
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM7, &TIM_TimeBaseStructure);
    TIM_UpdateRequestConfig(TIM7, TIM_UpdateSource_Regular);
    TIM_Cmd(TIM7, ENABLE);
    TIM_ITConfig(TIM7, TIM_IT_Update, ENABLE);//配置定时器更新中断,可以响应TIM7的溢出中断
}

stm32f10_it.h:

#include "stm32f10x_it.h"

extern void TimeDelay_Decrement(void);

void TIM7_IRQHandler(void)
{
    if(TIM_GetITStatus(TIM7, TIM_IT_Update) == SET){
        TIM_ClearITPendingBit(TIM7, TIM_FLAG_Update);
        GPIO_WriteBit(GPIOD, GPIO_Pin_2, (BitAction)(1-GPIO_ReadOutputDataBit(GPIOD, GPIO_Pin_2)));//定时时间到达后反转引脚电平
    }
}

疑惑:预分频数值为什么需要-1?

你可能感兴趣的:(STM32)