stm32呼吸灯代码
时间: 2023-10-11 13:06:29 浏览: 192
以下是一个基于STM32的呼吸灯代码示例:
```
#include "stm32f10x.h"
// 定义LED引脚
#define LED_PORT GPIOA
#define LED_PIN GPIO_Pin_1
// 初始化LED引脚为输出模式
void LED_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
}
// 呼吸灯效果
void LED_Breath(void)
{
uint16_t i;
// 呼吸灯效果循环
while (1)
{
// 从0到100逐渐增加PWM占空比
for (i = 0; i < 100; i++)
{
TIM_SetCompare1(TIM2, i);
delay_ms(5);
}
// 从100到0逐渐减小PWM占空比
for (i = 100; i > 0; i--)
{
TIM_SetCompare1(TIM2, i);
delay_ms(5);
}
}
}
int main(void)
{
// 初始化LED引脚
LED_GPIO_Config();
// 初始化定时器2
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 99; // PWM周期为100
TIM_TimeBaseStructure.TIM_Prescaler = 71; // 时钟预分频为72
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置TIM2的通道1为PWM输出模式
TIM_OCInitTypeDef TIM_OCInitStructure;
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_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_Cmd(TIM2, ENABLE); // 启动TIM2
// 启动呼吸灯效果
LED_Breath();
return 0;
}
// 延时函数,单位ms
void delay_ms(uint16_t ms)
{
uint16_t i, j;
for (i = 0; i < ms; i++)
for (j = 0; j < 1000; j++);
}
```
该代码使用定时器2的PWM输出模式实现呼吸灯效果。首先定义LED引脚为PA1,初始化为输出模式,然后配置定时器2的通道1为PWM输出模式,设置PWM周期为100,时钟预分频为72。接着实现呼吸灯效果循环,在循环中从0到100逐渐增加PWM占空比,再从100到0逐渐减小PWM占空比,每次变化后延时5毫秒。最后,在main函数中启动定时器2和呼吸灯效果。
阅读全文