stm32 f103呼吸灯
时间: 2023-10-21 11:06:58 浏览: 81
PWM呼吸灯_STM32F103_源码
要实现STM32F103呼吸灯效果,可以使用PWM输出控制LED的亮度。具体实现步骤如下:
1. 初始化TIM定时器和GPIO引脚。
2. 配置TIM定时器为PWM模式。
3. 在TIM中断服务函数中更新占空比,实现呼吸灯效果。
以下是示例代码:
```c
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_13
#define LED_GPIO GPIOC
#define LED_GPIO_CLK RCC_APB2Periph_GPIOC
#define TIM_PERIOD 1000
void TIM_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Period = TIM_PERIOD - 1;
TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
TIM_Cmd(TIM3, ENABLE);
}
void GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(LED_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_GPIO, &GPIO_InitStructure);
}
void TIM3_IRQHandler(void)
{
static uint16_t brightness = 0;
static uint8_t direction = 1;
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
if (direction)
{
brightness++;
if (brightness >= TIM_PERIOD)
{
direction = 0;
}
}
else
{
brightness--;
if (brightness == 0)
{
direction = 1;
}
}
TIM_SetCompare3(TIM3, brightness);
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
}
}
int main(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_Config();
TIM_Config();
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
while (1)
{
}
}
```
阅读全文