stm32f103c8t6呼吸灯pwm,2秒循环一次
时间: 2024-05-12 16:12:16 浏览: 121
STM32F103C8T6是一款常用的单片机芯片,呼吸灯是一种常见的LED效果,使用PWM来实现可以让LED呈现出类似于呼吸的效果。下面是实现2秒循环一次的呼吸灯效果的代码:
```
#include "stm32f10x.h"
void delay_ms(uint32_t ms)
{
uint32_t i;
for(i=0; i<ms*1000; i++);
}
int main()
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
// 使能TIM3和GPIOB时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// 设置GPIOB8引脚为TIM3的通道3
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置TIM3为PWM模式
TIM_TimeBaseStructure.TIM_Period = 1000; // 设置周期为1000
TIM_TimeBaseStructure.TIM_Prescaler = 720; // 设置预分频为720
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
// 配置TIM3通道3为PWM输出模式
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 500; // 设置占空比为50%
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
// 启动TIM3
TIM_Cmd(TIM3, ENABLE);
while(1)
{
for(int i=0; i<=1000; i+=20) // 呼吸灯升亮过程
{
TIM_SetCompare3(TIM3, i); // 设置占空比
delay_ms(10); // 延时10ms
}
for(int i=1000; i>=0; i-=20) // 呼吸灯降亮过程
{
TIM_SetCompare3(TIM3, i); // 设置占空比
delay_ms(10); // 延时10ms
}
delay_ms(2000); // 2秒循环一次
}
}
阅读全文