stm32 标准库 定时灯代码
时间: 2023-08-11 14:06:24 浏览: 69
嵌入式 stm32 使用软件STM32cubeIDE打开,STM32F4xx定时3点亮22个外设2812灯,带有设施模式功能
5星 · 资源好评率100%
以下是使用 STM32 标准库实现的定时灯代码:
```c
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_13
#define LED_PORT GPIOC
void init_timer(void);
void init_gpio(void);
int main(void) {
init_gpio();
init_timer();
while(1) {
}
return 0;
}
void init_gpio(void) {
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Pin = LED_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStruct);
}
void init_timer(void) {
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_Prescaler = 7200 - 1;
TIM_TimeBaseInitStruct.TIM_Period = 1000 - 1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
TIM_Cmd(TIM3, ENABLE);
}
void TIM3_IRQHandler(void) {
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) {
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
GPIO_WriteBit(LED_PORT, LED_PIN, !GPIO_ReadOutputDataBit(LED_PORT, LED_PIN));
}
}
```
代码中使用 TIM3 定时器来实现定时闪烁 LED,定时器的时钟频率为 72 MHz,预分频值为 7200 - 1,计数器周期为 1000 - 1,即每 1 秒触发一次定时器中断。在定时器中断中翻转 LED 灯的状态。
阅读全文