STM32F103ZET6 timer interrupt experiment
Article Directory
Preface
The learning of STM32 can be divided into 3 versions.
1. Register version
2. Library function version
3. HAL library version
Due to personal reasons, I choose the library function version to learn STM32.
Tip: Problems such as software installation will not be explained! ! !
1. The basic principle of timer
1. Resource introduction
2. General timer function
3. Introduction to counting mode
4. Working principle
2. Related registers
1. Control register 1 (TIMx_CR1)
2. DMA/interrupt enable register (TIMx_DIER)
3. Prescaler register (TIMx_PSC)
4. Auto reload register (TIMx_ARR)
5. Counter current value register (TIMx_CNT)
Three, operation steps
1. Overflow time calculation
2. Operation steps
Fourth, the program source code
1.timer.h
code show as below:
#ifndef __TIMER_H
#define __TIMER_H
#include "sys.h"
void TIM3_Int_Init(u16 arr,u16 psc);
#endif
2.timer.c
code show as below:
#include "timer.h"
#include "led.h"
void TIM3_Int_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef IM_TimeBaseInitstr;
NVIC_InitTypeDef NVIC_Initstr;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);//定时器时钟使能
IM_TimeBaseInitstr.TIM_Period=arr;
IM_TimeBaseInitstr.TIM_Prescaler=psc;
IM_TimeBaseInitstr.TIM_CounterMode=TIM_CounterMode_Up;
IM_TimeBaseInitstr.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM3, &IM_TimeBaseInitstr);//初始化时钟
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);//开启定时器中断
NVIC_Initstr.NVIC_IRQChannel=TIM3_IRQn;
NVIC_Initstr.NVIC_IRQChannelCmd=ENABLE;
NVIC_Initstr.NVIC_IRQChannelPreemptionPriority=0;
NVIC_Initstr.NVIC_IRQChannelSubPriority=2;
NVIC_Init(&NVIC_Initstr);//配置NVIC
TIM_Cmd(TIM3, ENABLE);//使能定时器
}
void TIM3_IRQHandler(void)//中断服务函数
{
if(TIM_GetITStatus(TIM3, TIM_IT_Update)==SET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);//清除更新中断标志
LED1=!LED1;
}
}
3.main.c
code show as below:
#include "stm32f10x.h"
#include "led.h"
#include "delay.h"
#include "beep.h"
#include "key.h"
#include "timer.h"
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
delay_init();
LED_Init();
Beep_Init();
KEY_Init();
TIM3_Int_Init(4999,7199);//间隔500ms
while(1)
{
LED2=!LED2;
delay_ms(200);
}
}
5. Experimental results
LED1 status reversal, interval 500ms; (timer)
LED2 status reversal, interval 200ms; (delay)
to sum up
adhere to! ! !