#蓝桥杯嵌入式#TIM配置

参考资料:
      蓝桥杯嵌入式备赛手册
总目录:目录

timc.c

  • 参考例程:Project->STM32F10x_StdPeriph_Examples->TIM->TimeBase下main.c
  • 复制①RCC_Configuration();不用选分频
  • ②NVIC_Configuration();
  • ③/* Time base configuration */并把Period改成999,Prescaler改成71。即定时器1ms进入一次中断
  • ④TIM_ITConfig(TIM2,TIM_IT_Update, ENABLE);改成Update
  • ⑤TIM_Cmd();配置为1ms中断
  • 即:
    #蓝桥杯嵌入式#TIM配置_第1张图片
    #蓝桥杯嵌入式#TIM配置_第2张图片
    #蓝桥杯嵌入式#TIM配置_第3张图片
    在这里插入图片描述
  • 同路径下stm32f10x_it.c,然后写中断函数
    #蓝桥杯嵌入式#TIM配置_第4张图片
  • 此外,为了体现中断,可以结合之前的LED(LED配置),在TIM中断函数中控制灯的亮灭
  • 综上,tim.c完整代码为:
#include "tim.h"
#include "led.h"

extern void Delay_Ms(u32 nTime);

void TIM_Init()
{
	NVIC_InitTypeDef NVIC_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
	
  /* Enable the TIM2 global Interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
	
	
  TIM_TimeBaseStructure.TIM_Period = 999;
  TIM_TimeBaseStructure.TIM_Prescaler = 71;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
	
  TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
  TIM_Cmd(TIM2, ENABLE);
}

//TIM_IT_Update
u8 status = 0;
u16 cnt = 0;
void TIM2_IRQHandler(void)
{
  if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
  {
    TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
		if(cnt++ == 500)
		{
			cnt = 0;
			led_Control(LED_ALL, status);
			status = !status;
		}
  }
}

main.c

#include "stm32f10x.h"
#include "lcd.h"
#include "led.h"
#include "tim.h"

u32 TimingDelay = 0;

void Delay_Ms(u32 nTime);

//Main Body
int main(void)
{
     
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	SysTick_Config(SystemCoreClock/1000);
	led_Init();
	TIM_Init();
	
	while(1);
}

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

你可能感兴趣的:(嵌入式(蓝桥杯))