STM32F1 的通用定时器是一个通过可编程预分频器(PSC)驱动的 16 位自动装载计数器(CNT)构成。
其中有4 个独立通道(TIMx_CH1~4),这些通道可以用来作为:
A.输入捕获
B.输出比较
C.PWM生成(边缘或中间对齐模式)
D.单脉冲模式输出
TIM1、8、9、10、11、15、16、17挂在APB2上
TIM2、3、4、5、6、7、12、13、14挂在APB1上
(1)使能时钟
(2)初始化定时器参数,设置自动重装值,分频系数,计数方式等
typedef struct
{
uint16_t TIM_Prescaler; //设置分频系数
/*!< Specifies the prescaler value used to divide the TIM clock.
This parameter can be a number between 0x0000 and 0xFFFF */
uint16_t TIM_CounterMode; //设置计数模式
/*!< Specifies the counter mode.
This parameter can be a value of @ref TIM_Counter_Mode */
uint16_t TIM_Period; //设置自动重载计数周期值
/*!< Specifies the period value to be loaded into the active
Auto-Reload Register at the next update event.
This parameter must be a number between 0x0000 and 0xFFFF. */
uint16_t TIM_ClockDivision; //设置时钟分频因子
/*!< Specifies the clock division.
This parameter can be a value of @ref TIM_Clock_Division_CKD */
uint8_t TIM_RepetitionCounter; //高级定时器时才有用
/*!< Specifies the repetition counter value. Each time the RCR downcounter
reaches zero, an update event is generated and counting restarts
from the RCR value (N).
This means in PWM mode that (N+1) corresponds to:
- the number of PWM periods in edge-aligned mode
- the number of half PWM period in center-aligned mode
This parameter must be a number between 0x00 and 0xFF.
@note This parameter is valid only for TIM1 and TIM8. */
} TIM_TimeBaseInitTypeDef;
(3)设置 TIM3_DIER允许更新中断(一开始忘记设置了,导致LED1不能闪烁)
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE);
(4)中断优先级设置
因为要产生中断,需要设置NVIC相关寄存器,设置中断优先级
(5)使能TIM3
(6)编写中断服务函数
void TIM3_IRQHandler(void)
{
if(TIM_GetITStatus(TIM3,TIM_IT_Update)!=RESET)//检查TIM中断是否发生
{
TIM_ClearITPendingBit(TIM3,TIM_IT_Update);//检测中断发生后,清除标志
LED1=!LED1;
}
}
中断服务函数名一般在startup_stm32f10xhd.s中,需要自己好好找
TIME.C文件
#include "TIME.h"
#include "led.h"
void TIM3_Int_Init(u16 arr,u16 psc)//arr自动重装载值,psc分频系数
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStucture;
NVIC_InitTypeDef NVIC_InitStucture;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
TIM_TimeBaseInitStucture.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStucture.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStucture.TIM_Period=arr;
TIM_TimeBaseInitStucture.TIM_Prescaler=psc;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStucture);
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE);
NVIC_InitStucture.NVIC_IRQChannel=TIM3_IRQn;
NVIC_InitStucture.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStucture.NVIC_IRQChannelPreemptionPriority=1;
NVIC_InitStucture.NVIC_IRQChannelSubPriority=1;
NVIC_Init(&NVIC_InitStucture);
TIM_Cmd(TIM3,ENABLE);
}
void TIM3_IRQHandler(void)
{
if(TIM_GetITStatus(TIM3,TIM_IT_Update)!=RESET)
{
TIM_ClearITPendingBit(TIM3,TIM_IT_Update);
LED1=!LED1;
}
}
main函数
#include "TIME.h"
#include "led.h"
#include "delay.h"
#include "stm32f10x.h"
int main(void)
{
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
LED_Init();
TIM3_Int_Init(4999,7199);
while(1)
{
LED0=!LED0;
delay_ms(200);
}
}