用stm32写一个流水灯实验代码,要求用tim定时器实现
时间: 2023-07-18 18:30:49 浏览: 686
好的,以下是一个基于STM32的流水灯实验代码,使用TIM定时器实现:
```c
#include "stm32f10x.h"
#define LED1 GPIO_Pin_8
#define LED2 GPIO_Pin_9
#define LED3 GPIO_Pin_10
#define LED4 GPIO_Pin_11
void TIM_Configuration(void);
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIOC clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
/* Configure PC8, PC9, PC10 and PC11 in output pushpull mode */
GPIO_InitStructure.GPIO_Pin = LED1 | LED2 | LED3 | LED4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
TIM_Configuration();
while (1)
{
}
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* TIM2 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period = 1000 - 1; // 1s
TIM_TimeBaseStructure.TIM_Prescaler = 7200 - 1; // 10ms
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
/* TIM2 interrupt enable */
TIM_ITConfig(TIM2, TIM_IT_Update, 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);
/* TIM2 enable counter */
TIM_Cmd(TIM2, ENABLE);
}
void TIM2_IRQHandler(void)
{
static uint8_t led_state = 0;
static uint16_t led_pin = LED1;
if (TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
GPIO_ResetBits(GPIOC, LED1 | LED2 | LED3 | LED4);
switch (led_state)
{
case 0:
led_pin = LED1;
break;
case 1:
led_pin = LED2;
break;
case 2:
led_pin = LED3;
break;
case 3:
led_pin = LED4;
break;
}
GPIO_SetBits(GPIOC, led_pin);
led_state++;
if (led_state > 3)
led_state = 0;
}
}
```
在这个实验中,我们使用了TIM2定时器来控制LED的流水效果。TIM2定时器的时钟频率为72MHz,我们将它的预分频器设置为7200-1,这样就可以将定时器的时钟频率降低到了10kHz。再将定时器的计数值设置为1000-1,这样定时器每计数到1000时,就会产生一次更新事件,触发定时器中断。
在定时器中断中,我们通过一个状态机来控制LED的流水效果。首先将所有LED灭掉,然后根据状态机的状态点亮一个LED。状态机的状态每次加1,当状态达到3时,状态归零。这样就可以实现LED的流水效果了。
希望这个实验能对你有所帮助!
阅读全文