stm32定时器中断实验

时间:2021-07-04 23:32:59

//个人总结:所有的中断实验都是设置好中断的条件,编写中断处理函数;之前是串口通信,当串口发送数据时,将数据打印出;后来是外部中断,这里用到了外部时钟,发生外部输入中断时,进行处理;看门狗(独立看门狗和窗口看门狗)都是在内部引起的MCU复位;这里的定时器中断,发生更新时,进行中断处理函数。


#include "stm32f4xx.h"


void delay(void);
void led_init(void);
void tim_init(u16 arr,u16 pre);
void TIM3_IRQHandler(void);

int main(){
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

led_init();
tim_init(5000-1,8400-1);

while(1){
delay();
GPIO_ResetBits( GPIOF, GPIO_Pin_10);
}
}


void delay(){
int i,j;
for(i=0;i<1000;i++)
for(j=0;j<10000;j++)
{}
}


void led_init(){
GPIO_InitTypeDef GPIO_InitStruct;

RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOF,ENABLE);

GPIO_InitStruct.GPIO_Mode=GPIO_Mode_OUT;
GPIO_InitStruct.GPIO_OType=GPIO_OType_PP;
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_10;
GPIO_InitStruct.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_InitStruct.GPIO_Speed=GPIO_Fast_Speed;

GPIO_Init(GPIOF, &GPIO_InitStruct);
}


void tim_init(u16 arr, u16 pre){  // ÕâÀïÓõ½ÁËTIM3£¬ÓÐÖжÏ
NVIC_InitTypeDef NVIC_InitStruct;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);

NVIC_InitStruct.NVIC_IRQChannel=TIM3_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=0X02;
NVIC_InitStruct.NVIC_IRQChannelSubPriority=0X02;

NVIC_Init(& NVIC_InitStruct);

TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_Period=arr;
TIM_TimeBaseInitStruct.TIM_Prescaler=pre;

TIM_TimeBaseInit( TIM3, & TIM_TimeBaseInitStruct);

TIM_ITConfig( TIM3,  TIM_IT_Update,  ENABLE); // 寄存器的相应位使能中断

// 中断定时器
TIM_Cmd(TIM3,ENABLE);
}


void TIM3_IRQHandler(void){
if(TIM_GetITStatus(TIM3,TIM_IT_Update)!=RESET){
GPIO_ResetBits( GPIOF, GPIO_Pin_9);
delay();
delay();
 GPIO_SetBits( GPIOF, GPIO_Pin_9);
}
TIM_ClearITPendingBit(TIM3,TIM_IT_Update);
}