stm32 利用PWM控制LED灯的亮度,从而实现聚光和泛光的效果的代码
时间: 2024-06-10 17:06:10 浏览: 142
下面是一个简单的示例代码:
```c
#include <stdio.h>
#include "stm32f10x.h"
#define LED_GPIO_PORT GPIOB
#define LED_GPIO_PIN GPIO_Pin_0
#define LED_ON() GPIO_SetBits(LED_GPIO_PORT, LED_GPIO_PIN)
#define LED_OFF() GPIO_ResetBits(LED_GPIO_PORT, LED_GPIO_PIN)
void PWM_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStructure);
}
void PWM_TIM_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 9999;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
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_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_Cmd(TIM3, ENABLE);
}
void Set_PWM_Cycle(int cycle)
{
int pulse = (cycle * 10000) / 255;
TIM3->CCR2 = pulse;
}
int main(void)
{
PWM_GPIO_Config();
PWM_TIM_Config();
while(1)
{
for(int i = 0; i <= 255; i++) {
Set_PWM_Cycle(i);
Delay(10);
}
for(int i = 255; i >= 0; i--) {
Set_PWM_Cycle(i);
Delay(10);
}
}
}
```
在这段代码中,我们使用了 TIM3 的 CH2 PWM 输出,并将其连接到了 PB0 引脚上的 LED。在 Set_PWM_Cycle 函数中,我们可以设置 PWM 的占空比,从而改变 LED 的亮度。
该代码通过循环递增和递减占空比的方式实现了灯的聚光和泛光效果。
阅读全文