编写一个用TIM定时器实现stm32的跑马灯实验代码,要能适用战舰3开发板
时间: 2024-03-09 10:48:15 浏览: 71
好的,以下是用TIM定时器实现stm32的跑马灯实验代码:
```c
#include "stm32f4xx.h"
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_InitStructure.TIM_Period = 500 - 1;
TIM_InitStructure.TIM_Prescaler = 42000 - 1;
TIM_InitStructure.TIM_ClockDivision = 0;
TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_InitStructure);
TIM_Cmd(TIM2, ENABLE);
}
void LED_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOF, &GPIO_InitStructure);
}
void Delay(__IO uint32_t nCount)
{
while(nCount--)
{
}
}
int main(void)
{
TIM_Configuration();
LED_Configuration();
uint16_t LED_GPIO_Pin[] = {GPIO_Pin_9, GPIO_Pin_10, GPIO_Pin_11, GPIO_Pin_12};
uint8_t LED_on_index = 0;
while(1)
{
if(TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) != RESET)
{
TIM_ClearFlag(TIM2, TIM_FLAG_Update);
GPIO_SetBits(GPIOF, LED_GPIO_Pin[LED_on_index]);
Delay(0xFFFFF);
GPIO_ResetBits(GPIOF, LED_GPIO_Pin[LED_on_index]);
if(++LED_on_index >= 4)
{
LED_on_index = 0;
}
}
}
}
```
这份代码使用了TIM2定时器,将其预分频为42000,计数器自动重载值为500,每次计数器溢出时,会通过中断来触发LED的跑马灯效果。注意,这份代码使用的是战舰3开发板上的PF9, PF10, PF11, PF12四个IO口,你需要根据实际硬件资源进行修改。
阅读全文