stm32定时器 流水灯
时间: 2023-10-10 10:09:47 浏览: 259
对于在STM32上实现流水灯效果,可以使用定时器来控制LED的闪烁频率。以下是一个基本的流水灯示例程序,使用了TIM2定时器来控制LED的闪烁频率:
```c
#include "stm32f4xx.h"
void GPIO_Init(void)
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_InitStruct);
}
void TIM2_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_InitStruct;
TIM_InitStruct.TIM_Prescaler = 41999; // 设置预分频值,得到1ms的定时周期
TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_InitStruct.TIM_Period = 999; // 设置计数器最大值,得到1s的定时周期
TIM_InitStruct.TIM_ClockDivision = 0;
TIM_InitStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_InitStruct);
TIM_Cmd(TIM2, ENABLE);
}
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
static uint8_t ledIndex = 0;
static uint16_t ledValue = GPIO_Pin_12;
GPIO_SetBits(GPIOD, ledValue);
if (ledIndex == 0)
{
GPIO_ResetBits(GPIOD, GPIO_Pin_15);
ledValue = GPIO_Pin_12;
}
else
{
GPIO_ResetBits(GPIOD, ledValue >> 1);
ledValue <<= 1;
}
if (++ledIndex > 3)
{
ledIndex = 0;
}
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
int main(void)
{
GPIO_Init();
TIM2_Init();
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
while (1)
{
}
}
```
上述代码中,我们首先初始化了GPIOD的引脚作为输出,用于连接LED。然后,我们初始化了TIM2定时器,设置了预分频和计数器最大值,使得定时器的计数周期为1ms。在定时器中断处理函数中,控制LED的闪烁效果。最后,在主函数中使能了TIM2的中断,并进入了一个无限循环。
阅读全文