LED调光 LED调光,自然而然联想到PWM调光,通过改变脉冲宽度实现无极调光。原理许多博客都有介绍与讲解,此处不再赘述。关于定时器的配置程序如下。
//TIM配置
void TIM_Light_Configuration()
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
//时钟初始化
TIM_DeInit(TIM1);
TIM_DeInit(TIM14);
/*
APB2负责AD,I/O,高级TIM,串口1
APB1负责DA,USB,SPI,I2C,CAN,串口2345,普通TIM
*/
/* TIMx clock enable */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB ,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 |RCC_APB2Periph_TIM14,ENABLE);
//TIM1的PWM功能配置
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_0 | GPIO_Pin_1; //TIM1_CH1N TIM1_CH2N TIM1_3N
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//配置指定管脚的复用功能
GPIO_PinAFConfig(GPIOB, GPIO_PinSource0,GPIO_AF_2); //TIM1_CH2N
GPIO_PinAFConfig(GPIOB, GPIO_PinSource1,GPIO_AF_0); //TIM14_CH1
// GPIO_PinAFConfig(GPIOB, GPIO_PinSource13,GPIO_AF_2); //TIM1_CH3N WIFI指示灯
TIM_TimeBaseStructure.TIM_Period = 1000-1; //预装载arr
TIM_TimeBaseStructure.TIM_Prescaler = 3; //预分频2k PWM频率
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; //重复寄存器,用于自动更新PWM占空比
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_TimeBaseInit(TIM14, &TIM_TimeBaseStructure);
/*
TIM_OCInitTypeDef.TIM_OCMode = TIM_OCMode_PWM1:
当计时器值小于比较器设定值时TIMX输出脚此时输出有效高电平,反之为低电平
TIM_OCInitTypeDef.TIM_OCMode = TIM_OCMode_PWM2:
当计时器值大于比较器设定值时TIMX输出脚此时输出有效高电平,反之为低电平
*/
//PWM设置
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_Pulse = 0; //CCR,设置占空比
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //正向通道有效
TIM_OC1Init(TIM14, &TIM_OCInitStructure); //黄灯
//PWM设置
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_Pulse = 0; //CCR,设置占空比
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Disable; //正向通道无效
//高级定时器参数
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low; //互补端极性
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; //反向通道有效
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset; //死区后输出状态
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; //死区后互补端输出状态
TIM_OC2Init(TIM1, &TIM_OCInitStructure); //白灯
//预装载
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC1PreloadConfig(TIM14, TIM_OCPreload_Enable);
//Ê使能TIMx在ARR上的预装载寄存器
TIM_ARRPreloadConfig(TIM1, ENABLE);
TIM_ARRPreloadConfig(TIM14, ENABLE);
/* TIM1 counter enable */
TIM_Cmd(TIM1, ENABLE);
TIM_Cmd(TIM14, ENABLE);
/* TIM1 Main Output Enable */
TIM_CtrlPWMOutputs(TIM1, ENABLE);
TIM_CtrlPWMOutputs(TIM14, ENABLE);
}
|