在keil5中用stm32f103c8t6 实现pwm呼吸灯的工程代码
时间: 2023-09-07 08:12:46 浏览: 46
pwm呼吸灯stm32工程代码
好的,以下是一个简单的在Keil5中使用STM32F103C8T6实现PWM呼吸灯的工程代码:
```c
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_13
#define LED_GPIO_PORT GPIOC
#define LED_GPIO_CLK RCC_APB2Periph_GPIOC
#define TIM_PERIOD 255
void GPIO_Configuration(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_PORT, &GPIO_InitStructure);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Period = TIM_PERIOD;
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_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_Cmd(TIM3, ENABLE);
}
void delay(uint32_t n)
{
while(n--)
{
__NOP();
}
}
int main(void)
{
uint8_t duty_cycle = 0;
uint8_t direction = 1;
GPIO_Configuration();
TIM_Configuration();
while(1)
{
TIM_SetCompare3(TIM3, duty_cycle);
if(duty_cycle == 0)
{
direction = 1;
}
else if(duty_cycle == TIM_PERIOD)
{
direction = -1;
}
duty_cycle += direction;
delay(20000);
}
}
```
在这个代码中,我们使用了STM32F103C8T6的Timer3和PWM输出来控制LED的亮度。我们通过一个死循环来改变占空比,从而实现呼吸灯的效果。请注意,我们使用了TIM_PERIOD来设置PWM的周期,这里设置为255,即PWM的最大值。我们还使用了72-1来预分频Timer3的时钟,这样计数器每计数一次,就会产生一个时钟周期,即1us。在while循环中,我们使用了delay函数来降低占空比改变的速度,以便更好地观察呼吸灯的效果。
希望这个代码可以帮助到你!
阅读全文