实验内容:用基本定时器TIM6中断来实现LED灯1s的闪烁
1.初始化LED灯的GPIO
#include "led.h"
void LED_Init()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOE, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOE, &GPIO_InitStructure);
}
2.初始化定时器6,配置周期和预分频值,开启中断
#include "timer.h"
void TIM6_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
TIM_TimeBaseInitStructure.TIM_Period = arr;
TIM_TimeBaseInitStructure.TIM_Prescaler = psc;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM6, &TIM_TimeBaseInitStructure);
NVIC_InitStructure.NVIC_IRQChannel = TIM6_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init( &NVIC_InitStructure);
TIM_ClearFlag(TIM6, TIM_IT_Update);//清除计数器中断标志位
TIM_ITConfig(TIM6, TIM_IT_Update, ENABLE);// 开启计数器中断
TIM_Cmd(TIM6, ENABLE);//使能计数器
}
3.在stm32f10x_it编写中断服务函数
void TIM6_IRQHandler()
{
if(TIM_GetITStatus(TIM6, TIM_IT_Update)!= RESET)//中断到来
{
LED1=!LED1;
TIM_ClearITPendingBit(TIM6, TIM_IT_Update);//清除中断标志位
}
}
4.编写main函数
#include "stm32f10x.h"
#include "led.h"
#include "delay.h"
#include "timer.h"
int main()
{
LED_Init();
delay_init();
TIM6_Init(9999,3599);
LED1=1;
while(1)
{
}
}