STM32——基本定时器实验

实验内容:用基本定时器TIM6中断来实现LED灯1s的闪烁

1.初始化LED灯的GPIO

#include "led.h"
void LED_Init()
{
  GPIO_InitTypeDef        GPIO_InitStructure;
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOE, ENABLE);
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;    
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;    
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_Init(GPIOE, &GPIO_InitStructure);
}

2.初始化定时器6,配置周期和预分频值,开启中断

#include "timer.h"
void TIM6_Init(u16 arr,u16 psc) 
{
    TIM_TimeBaseInitTypeDef       TIM_TimeBaseInitStructure;
	NVIC_InitTypeDef              NVIC_InitStructure;
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
	
	TIM_TimeBaseInitStructure.TIM_Period = arr;
	TIM_TimeBaseInitStructure.TIM_Prescaler = psc;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM6, &TIM_TimeBaseInitStructure);
	
	NVIC_InitStructure.NVIC_IRQChannel = TIM6_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init( &NVIC_InitStructure);
	
	TIM_ClearFlag(TIM6, TIM_IT_Update);//清除计数器中断标志位
	
	TIM_ITConfig(TIM6, TIM_IT_Update, ENABLE);// 开启计数器中断
	
	TIM_Cmd(TIM6, ENABLE);//使能计数器
}

3.在stm32f10x_it编写中断服务函数

void TIM6_IRQHandler()
{
   if(TIM_GetITStatus(TIM6, TIM_IT_Update)!= RESET)//中断到来
	 {
		  LED1=!LED1;
		  TIM_ClearITPendingBit(TIM6, TIM_IT_Update);//清除中断标志位
	 }
	
}

4.编写main函数

#include "stm32f10x.h"
#include "led.h"
#include "delay.h"
#include "timer.h"

int main()
{
   LED_Init();
   delay_init();
   TIM6_Init(9999,3599);
   LED1=1;
   while(1)
   {
   }
    
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

%Zero%

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值