用STM32写一个利用定时器控制LED灯以10Hz频率亮灭闪烁;
时间: 2023-06-11 19:05:59 浏览: 172
用定时器中断闪灯,定时器中断的学习_定时器控制STM32_ledp10_源码
好的,以下是基于STM32F1系列芯片的代码示例:
```c
#include "stm32f10x.h"
void delay_ms(uint32_t ms) {
while(ms--) {
for (uint32_t i = 0; i < 7200; i++);
}
}
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
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);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 36000 - 1; // 定时器周期为 1s / 36000 = 27.78us
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1; // 预分频系数为 72,计数时钟为 1MHz
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM2, ENABLE);
while (1)
{
// 循环等待中断
}
}
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
static uint8_t ledState = 0;
if (ledState == 0) {
GPIO_SetBits(GPIOC, GPIO_Pin_13); // 点亮LED
ledState = 1;
} else {
GPIO_ResetBits(GPIOC, GPIO_Pin_13); // 熄灭LED
ledState = 0;
}
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
```
上述代码中,使用 TIM2 定时器,设置定时器周期为 1s,预分频系数为 72,计数时钟为 1MHz。在定时器中断中,控制 LED 灯的亮灭状态。通过循环等待中断的方式,可以让程序一直运行下去。需要注意的是,定时器的计数值是从 0 开始的,因此需要在定时器中断处理函数中,通过一个状态变量来记录 LED 灯的当前状态。
阅读全文