1.STM32的通用定时器是可编程预分频驱动的16位自动装载计数器。
(3)预分频寄存器(TIMx_PSC):该寄存器用来设置对时钟的分频。
(4)自动重装载寄存器(TIMx_ARR):
(5) 状态寄存器(TIMx_SR):
3.设计思路:通过设置设置通用定时器的中断,并在定时器中断服务函数中反转LED灯。首先,使能定时器的时钟。然后,配置定时器的相关信息 和中断管理的相关信息。最后,编写定时器中断的中断服务函数。
4.代码:
(1)LED:
#ifndef __LED_H
#define __LED_H
#include "stm32f10x.h"
void LED_Init(void);
#endif
#include "led.h"
void LED_Init(void)
{
//¶¨Òå¶Ë¿ÚµÄ½á¹¹Ìå:
GPIO_InitTypeDef GPIO_InitStruct;
//1.ʹÄÜʱÖÓ£º
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOA,ENABLE);
//2.ÅäÖö˿ڽṹÌåµÄÏà¹ØÐÅÏ¢£º£¨LED1£©
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOD,&GPIO_InitStruct);
//ÅäÖÃLED0£º
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_8;
GPIO_Init(GPIOA,&GPIO_InitStruct);
//³õʼʱ½«LEDµÄ¶Ë¿Ú¶¼ÖÃΪ1£¬¼´Ï¨Ãð
GPIO_SetBits(GPIOA,GPIO_Pin_8);
GPIO_SetBits(GPIOD,GPIO_Pin_2);
}
(2)TIME:
#ifndef __TIME_H
#define __TIME_H
#include "stm32f10x.h"
void TIME_Init(u16 arr,u16 psc);
#endif
#include "time.h"
void TIME_Init(u16 arr,u16 psc)
{
//¶¨Ò嶨ʱÆ÷ºÍÖжϽṹÌ壺
TIM_TimeBaseInitTypeDef TIM_TimBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
//1.ʹÄܶ¨Ê±Æ÷ʱÖÓ;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
//2.³õʼ»¯time3£º
TIM_TimBaseStructure.TIM_Period = arr; //ÉèÖÃ×Ô¶¯ÖØ×°ÔؼĴæÆ÷µÄÖµ
TIM_TimBaseStructure.TIM_Prescaler = psc;
TIM_TimBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimBaseStructure.TIM_CounterMode = TIM_CounterMode_Down;
TIM_TimeBaseInit(TIM3,&TIM_TimBaseStructure);
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); //ÔÊÐí¸üÐÂÖжÏ
//3.ÖжÏÅäÖãº
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStructure);
//4.ʹÄܶ¨Ê±Æ÷£º
TIM_Cmd(TIM3,ENABLE);
}
//ÖØдtime3µÄÖжϷþÎñº¯Êý£º
void TIM3_IRQHandler(void)
{
static int i = 0;
//¼ì²éÊÇ·ñ·¢ÉúÖжϣº
if(TIM_GetITStatus(TIM3,TIM_IT_Update) != RESET)
{
//Çå³ýtimeµÄ¸üÐÂÖжϱê־λ
TIM_ClearITPendingBit(TIM3,TIM_IT_Update);
if(i)
{
GPIO_SetBits(GPIOA,GPIO_Pin_8);
i = !i;
}
else
{
GPIO_ResetBits(GPIOA,GPIO_Pin_8);
i = !i;
}
}
}
(3)main:
#include "stm32f10x.h"
#include "delay.h"
#include "led.h"
#include "time.h"
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
LED_Init();
TIME_Init(4999,7199);
while(1)
{
delay_ms(1000);
}
}
5.运行结果:
文章来源:https://www.toymoban.com/news/detail-628721.html
6.总结:本次实验是通过STM32的通用定时器反转LED灯。在实验库函数编程的时候,是比较方便的。但是,为了打好基础,应该去大概的了解一下相关寄存器的功能。文章来源地址https://www.toymoban.com/news/detail-628721.html
到了这里,关于STM32入门学习之定时器中断的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!