基本框架
1. 配置定时器时钟
在 stm32f10x_rcc.h 头文件中查找相关函数函数
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
2. 配置定时器结构体
在 stm32f10x_tim.h 头文件中查找相关函数函数
TIM_TimeBaseInitTypeDef timInitStructure;
timInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
timInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
timInitStructure.TIM_Period = 10000-1;
timInitStructure.TIM_Prescaler = 7200-1;
3. 开启定时器中断
在 stm32f10x_tim.h 头文件中查找相关函数函数
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
4. 配置中断结构体
在 misc.h 头文件中查找相关函数函数
TIM2_IRQn 在 stm32f10x.h 头文件中可以查找到
NVIC_InitTypeDef nvicInitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
nvicInitStructure.NVIC_IRQChannel = TIM2_IRQn;
nvicInitStructure.NVIC_IRQChannelPreemptionPriority = 1;
nvicInitStructure.NVIC_IRQChannelSubPriority = 1;
nvicInitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvicInitStructure);
5. 搭建定时器中断服务函数
void TIM2_IRQHandler(void)
{
static uint16_t t = 0;
if( TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
if(t++ %2 == 1)
{
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
}
else
{
GPIO_SetBits(GPIOC, GPIO_Pin_13);
}
}
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
闪烁灯代码整合
tim.c
#include "tim.h"
#include "stm32f10x.h"
void tim_Init(void)
{
TIM_TimeBaseInitTypeDef timInitStructure;
NVIC_InitTypeDef nvicInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
timInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
timInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
timInitStructure.TIM_Period = 10000-1;
timInitStructure.TIM_Prescaler = 7200-1;
TIM_TimeBaseInit(TIM2, &timInitStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
nvicInitStructure.NVIC_IRQChannel = TIM2_IRQn;
nvicInitStructure.NVIC_IRQChannelPreemptionPriority = 1;
nvicInitStructure.NVIC_IRQChannelSubPriority = 1;
nvicInitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvicInitStructure);
}
tim.h
#include "stm32f10x.h"
void tim_Init(void);
main.c
#include "stm32f10x.h"
#include "main.h"
#include "led.h"
#include "shake.h"
#include "relay.h"
#include "exti.h"
#include "usart.h"
#include "tim.h"
void delay(uint16_t time)
{
uint16_t i=0;
while(time--)
{
i=10000;
while(i--);
}
}
int main()
{
LED_Init();
tim_Init();
GPIO_SetBits(GPIOC, GPIO_Pin_13);
while(1)
{
}
}
void TIM2_IRQHandler(void)
{
static uint16_t t = 0;
if( TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
if(t++ %2 == 1)
{
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
}
else
{
GPIO_SetBits(GPIOC, GPIO_Pin_13);
}
}
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
1秒闪烁灯
|