# 蓝桥嵌入式之 TIM的定时中断_Again

### 一、主要代码

main.c

/*******************************************************************************
* 文件名：main.c
* 描  述：
* 作  者：CLAY
* 版本号：v1.0.0
* 日  期: 2019年2月19日
* 备  注：修改后的LCD例程
*         采用定时器实现的简单1s计时，并显示到LCD上
*******************************************************************************
*/

#include "stm32f10x.h"
#include "lcd.h"
#include "e2prom.h"
#include "stdio.h"
#include "i2c.h"
#include "rtc.h"
#include "usart2.h"
#include "pwm.h"
#include "pwm_oc.h"
#include "pwm_ic.h"
#include "timer.h"

u32 TimingDelay = 0;
u8 RxdCnt = 0;
u8 RxdOver = 0;
u8 RxdBuf[20];
void Delay_Ms(u32 nTime);
u8 RTC_Flag = 0;
u32 tmr = 0;

//Main Body
int main(void)
{
u8 str[20];

STM3210B_LCD_Init();
LCD_Clear(Blue);
LCD_SetBackColor(Blue);
LCD_SetTextColor(White);

SysTick_Config(SystemCoreClock/1000);

//PWM_Init(500, 60);//500Hz 60%方波//PA1
PWM_OC_Init(500, 60);//500Hz 60%方波 PA1
PWM_IC_Init();//PA7

TIM4_Init(10000, 7200);//定时1s

while(1)
{
sprintf((char *)str, "     %d    ", tmr);
LCD_DisplayStringLine(Line5, str);
}
}

//
void Delay_Ms(u32 nTime)
{
TimingDelay = nTime;
while(TimingDelay != 0);
}



timer.c

#include "stm32f10x.h"

void TIM4_Init(u16 period, u16 prescaler)
{
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);

TIM_TimeBaseStructure.TIM_Period = period-1;//总的值设置为0xFFFF
TIM_TimeBaseStructure.TIM_Prescaler = prescaler-1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

TIM_Cmd(TIM4, ENABLE);//开启定时器
TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);//开启定时器更新中断
}



timer.h

#ifndef _TIMER_H
#define _TIMER_H

void TIM4_Init(u16 period, u16 prescaler);

#endif



stm32f10x_it.c

...
extern 	u32 tmr;
void TIM4_IRQHandler(void)
{
if(TIM_GetITStatus(TIM4, TIM_IT_Update) == SET)
{
TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
tmr++;
if(tmr >= 9999)
{
tmr = 0;
}
}
}
...