用标准库函数设计编程实现控制灯光开关和亮度,stm32f103xc8t6实验板上就是能够用灯的开关和频闪的快慢来模拟,请给出具体代码
时间: 2024-04-01 20:32:09 浏览: 17
好的,下面是使用标准库函数实现控制灯光开关和亮度的代码。在这个例子中,我们将使用PB12引脚来控制LED灯的开关和亮度。
```c
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_tim.h"
#define LED_PIN GPIO_Pin_12
#define LED_PORT GPIOB
void LED_Init(void);
void LED_On(void);
void LED_Off(void);
void LED_Toggle(void);
void TIM2_Init(void);
void TIM2_PWM_SetDutyCycle(uint16_t duty_cycle);
int main(void)
{
// 初始化LED灯和定时器2
LED_Init();
TIM2_Init();
while(1)
{
// 控制LED灯开关
LED_Toggle();
// 控制LED灯亮度
TIM2_PWM_SetDutyCycle(500);
Delay(1000);
TIM2_PWM_SetDutyCycle(1000);
Delay(1000);
}
}
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
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 LED_On(void)
{
GPIO_SetBits(LED_PORT, LED_PIN);
}
void LED_Off(void)
{
GPIO_ResetBits(LED_PORT, LED_PIN);
}
void LED_Toggle(void)
{
GPIO_ToggleBits(LED_PORT, LED_PIN);
}
void TIM2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
// 打开定时器2和GPIOA时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// 配置TIM2_CH2的GPIO引脚
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);
// 配置计数器时钟
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = 71;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置PWM输出模式
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(TIM2, &TIM_OCInitStructure);
// 开启计数器
TIM_Cmd(TIM2, ENABLE);
}
void TIM2_PWM_SetDutyCycle(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_OC2Init(TIM2, &TIM_OCInitStructure);
}
```
上述代码中,LED_Init()函数用于初始化LED灯的GPIO引脚,TIM2_Init()函数用于初始化定时器2,TIM2_PWM_SetDutyCycle()函数用于设置PWM输出的占空比,实现LED灯的亮度控制。在main函数中,我们使用LED_Toggle()函数来控制LED灯的开关,使用TIM2_PWM_SetDutyCycle()函数来控制LED灯的亮度。由于使用了定时器2的PWM输出功能,所以灯的亮度可以在0到1000之间进行调节。
希望这个例子能对您有所帮助。