编写定时器 TIM2 驱动程序、定时器TIM2 中断配置程序和中断服务程序,实现LED 灯 12s 延时闪烁,画出定时器延时流程图。
时间: 2023-06-05 14:04:42 浏览: 207
Proteus仿真STM32定时器TIM2与中断来控制流水灯的定时闪烁。
好的,这个问题属于技术问题,我可以为您提供答案。以下是实现LED灯闪烁的代码:
```
#include "stm32f10x.h"
void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period = 24000 - 1; // 24000 * 0.5ms = 12s
TIM_TimeBaseStructure.TIM_Prescaler = 7199; // 72MHz / 7200 = 10kHz
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
/* TIM2 enable 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_ITConfig(TIM2, TIM_IT_Update, ENABLE);
/* TIM2 enable counter */
TIM_Cmd(TIM2, ENABLE);
}
void LED_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
/* Configure PC13 in output push-pull mode */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
int main(void)
{
/* Configure TIM2 and LED */
TIM2_Configuration();
LED_Configuration();
while(1);
}
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
/* Toggle LED */
GPIO_WriteBit(GPIOC, GPIO_Pin_13, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIOC, GPIO_Pin_13)));
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
```
定时器的中断处理函数如下:
```
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
/* Toggle LED */
GPIO_WriteBit(GPIOC, GPIO_Pin_13, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIOC, GPIO_Pin_13)));
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
```
定时器的延时流程图如下:
希望能回答您的问题,如有需要请随时联系我。
阅读全文