stm32实现呼吸流水灯
时间: 2023-09-26 15:11:31 浏览: 64
沁恒CH32V307呼吸流水灯
以下是使用STM32实现呼吸流水灯的代码:
```
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_12
#define LED_PORT GPIOB
void delay(uint32_t ms)
{
for (volatile uint32_t i = 0; i < ms * 1000; i++);
}
void init_led_gpio(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
}
void pwm_set_duty_cycle(uint16_t duty_cycle)
{
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = duty_cycle;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
}
void init_pwm_timer(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 9999;
TIM_TimeBaseStructure.TIM_Prescaler = 719;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
pwm_set_duty_cycle(0);
TIM_Cmd(TIM3, ENABLE);
}
void breath_led(void)
{
uint16_t duty_cycle = 0;
uint16_t direction = 1;
while (1)
{
pwm_set_duty_cycle(duty_cycle);
if (direction == 1)
{
duty_cycle++;
if (duty_cycle >= 10000)
{
direction = 0;
}
}
else
{
duty_cycle--;
if (duty_cycle == 0)
{
direction = 1;
}
}
delay(10);
}
}
int main(void)
{
init_led_gpio();
init_pwm_timer();
breath_led();
return 0;
}
```
该代码使用了定时器TIM3和PWM输出来实现呼吸灯效果。在循环中不断调整PWM占空比,从而实现灯光亮度的逐渐变化。具体来说,当占空比从0逐渐增加到10000时,灯光会逐渐变亮;当占空比从10000逐渐减小到0时,灯光会逐渐变暗。通过不断循环这个过程,就可以实现呼吸流水灯的效果。
阅读全文