STM32定时器中断-库函数

程序要求:通过定时器中断配置,每500ms中断一次,然后中断服务函数中控制LED实现LED1状态取反

下面给出几个主要文件的程序模板

timer.h:
 

#ifndef __TIMER_H
#define __TIMER_H
#include "sys.h"

void TIM3_init(u16 arr, u16 psc);

#endif

 

timer.c

#include "timer.h"
#include "led.h"

//tim的相关函数去stm32f4xx_tim.h中去找

void TIM3_init(u16 arr, u16 psc)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //使能定时器时钟

    TIM_TimeBaseInitStructure.TIM_Prescaler = psc; //预分频系数=psc
    TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //计数模式
    TIM_TimeBaseInitStructure.TIM_Period = arr; //自动装载值=arr
    TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //(这里没有太大作用)
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure); //初始化定时器,配置ARR,PSR

    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); //开启中断(定时器3,更新中断,ENABLE),使能定时器3的更新中断

    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //定时器x中断
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x03; //子优先级3
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01; //抢占优先级1
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure); //开启定时器中断,配置NVIC

    TIM_Cmd(TIM3, ENABLE); //使能定时器

}


void TIM3_IRQHandler(void) //编写中断服务函数
{
    if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
    {
        LED1 = !LED1;
        TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
    }
}

 

main.c

#include "led.h"
#include "sys.h"
#include "usart.h"
#include "delay.h"
#include "timer.h"

//通过定时器中断配置,每500ms中断一次,然后中断服务函数中控制LED实现LED1状态取反
int main()
{
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	delay_init(168);
	LED_Init();
	TIM3_init(5000-1, 8400-1);
	//溢出时间(Tout)的计算=(arr+1)*(psc+1)/Tclk
	//Tclk是定时器预分频前的时钟,是APB1的时钟经过倍频1/2后得到
	//f(频率)=Tclk/(psc+1)
	//T(周期)=1/f=(psc+1)/Tclk
	//Tout(溢出时间)=(arr+1)*T
	while (1) 
	{
		LED0 = !LED0;
		delay_ms(200);
	}
	
}

 

你可能感兴趣的:(STM32基础实验)