最近再做一个带蓝牙接口的血压计项目,项目中使用了STM32F10364引脚的MCU,在硬件设计中,因为外设较多,导致每个通用定时器至少有两个PWM输出引脚被占用,现在要控制RGB灯,只能用一个普通IO引脚模拟PWM输出。
相关的硬件电路设置如下:
GPIOA1------------------------------RGBBLUE灯
GPIOB1------------------------------RGBGREEN灯
GPIOD2------------------------------RGBRED灯
RGB灯采用了共阳极电路,所以在PWM的输出急性设置时,将极性设置为高电平,定时器的初始化如下图所示:
void initLedTimer( void ){
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_DeInit( TIM2 );
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure );
TIM_TimeBaseStructure.TIM_Period =TIMER_PERIOD;
TIM_TimeBaseStructure.TIM_Prescaler =TIMER_PRESCALER;
TIM_TimeBaseStructure.TIM_ClockDivision= TIM_CKD_DIV1; // 不分频
TIM_TimeBaseStructure.TIM_CounterMode =TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);
TIM_OCStructInit(&TIM_OCInitStructure );
TIM_OCInitStructure.TIM_OCMode =TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState =TIM_OutputState_Disable;
TIM_OCInitStructure.TIM_Pulse =DEFAULT_DUTY_CYCLE;
TIM_OCInitStructure.TIM_OCPolarity =TIM_OCPolarity_High;
//
TIM_OC1Init(TIM2,&TIM_OCInitStructure);
//
TIM_OC1PreloadConfig(TIM2,TIM_OCPreload_Enable);
//
TIM_OC2Init(TIM2,&TIM_OCInitStructure);
//
TIM_OC2PreloadConfig(TIM2,TIM_OCPreload_Enable);
//
TIM_OC3Init(TIM3,&TIM_OCInitStructure);
//
TIM_OC3PreloadConfig(TIM3,TIM_OCPreload_Enable);
//
TIM_OC4Init(TIM3,&TIM_OCInitStructure);
//
TIM_OC4PreloadConfig(TIM3,TIM_OCPreload_Enable);
//
TIM_OCStructInit(&TIM_OCInitStructure );
TIM_OCInitStructure.TIM_OCMode =TIM_OCMode_Timing;
TIM_OCInitStructure.TIM_Pulse =DEFAULT_DUTY_CYCLE;
//
TIM_OC2Init(TIM3,&TIM_OCInitStructure);
//
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);
// ARR重装载使能
TIM_ARRPreloadConfig(TIM2,ENABLE);
TIM_ARRPreloadConfig(TIM3,ENABLE);
//
TIM_ClearITPendingBit( TIM2,TIM_IT_Update );
TIM_ClearITPendingBit( TIM3,TIM_IT_Update | TIM_IT_CC2 );
//定时器2和3中断使能
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
TIM_ITConfig(TIM3,TIM_IT_Update |TIM_IT_CC2, ENABLE);
}
输出极性为高电平的意思就是说,假如说占空比为20%,那么他表示,低电平占整个周期20%的时间,反之如果设置极性为低电平,那么表示高电平占用整个周期的20%。
如何用GPIOD2模拟PWM波形呢? 关键的地方就是同时必须使用定时器中断 |