在keil5中用stm32f103c8t6 实现pwm呼吸灯的工程代码
时间: 2023-09-07 09:13:27 浏览: 108
PWM呼吸灯_STM32F103_源码
好的,以下是基于Keil5和STM32F103C8T6的PWM呼吸灯工程代码:
```
#include "stm32f10x.h"
void PWM_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
// 开启TIM2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
// 开启GPIOA时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置GPIOA.1为复用推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置TIM2
TIM_TimeBaseStructure.TIM_Period = 999; // 定时器周期为1000
TIM_TimeBaseStructure.TIM_Prescaler = 719; // 分频系数为720
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置TIM2通道1为PWM模式
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0; // 初始占空比为0
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
// 使能TIM2
TIM_Cmd(TIM2, ENABLE);
}
int main(void)
{
PWM_Configuration();
uint16_t duty_cycle = 0;
uint8_t direction = 1;
while (1)
{
TIM_SetCompare1(TIM2, duty_cycle);
if (duty_cycle == 999) {
direction = 0;
}
else if (duty_cycle == 0) {
direction = 1;
}
if (direction == 1) {
duty_cycle += 10;
}
else {
duty_cycle -= 10;
}
for (int i = 0; i < 100000; i++); // 延时
}
}
```
这段代码使用了TIM2的通道1来输出PWM信号,使用了GPIOA.1作为输出引脚。在主循环中,通过改变占空比的大小来实现呼吸灯的效果。
阅读全文