本帖最后由 sy12138 于 2022-12-30 13:42 编辑
#技术资源# #申请原创# #每日话题#
今天简单讲一哈定时器级联应用之一-周期门控
原理也很简单,例如我们使用TIM2、TIM3、TIM4三个定时器,用TIM2控制TIM3,TIM3控制TIM4。
配置也比较容易,使能TIM2、TIM3的主从模式,选择TIM2、TIM3的主模式选择更新事件触发输出,TIM3、TIM4从模式选择门控模式,并且TIM3触发源选择TIM2、TIM4触发源选择TIM3,这样我们就可以实现TIM2门控TIM3,TIM3门控TIM4了。
代码配置:
TIM_TimeBaseStructure.Period = 255;
TIM_TimeBaseStructure.Prescaler = 0;
TIM_TimeBaseStructure.ClkDiv = 0;
TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
TIM_InitTimeBase(TIM2, &TIM_TimeBaseStructure);
TIM_TimeBaseStructure.Period = 3;
TIM_InitTimeBase(TIM3, &TIM_TimeBaseStructure);
TIM_TimeBaseStructure.Period = 3;
TIM_InitTimeBase(TIM4, &TIM_TimeBaseStructure);
/* Master Configuration in PWM1 Mode */
TIM_OCInitStructure.OcMode = TIM_OCMODE_PWM1;
TIM_OCInitStructure.OutputState = TIM_OUTPUT_STATE_ENABLE;
TIM_OCInitStructure.Pulse = 64;
TIM_OCInitStructure.OcPolarity = TIM_OC_POLARITY_HIGH;
TIM_InitOc1(TIM2, &TIM_OCInitStructure);
/* Select the Master Slave Mode */
TIM_SelectMasterSlaveMode(TIM2, TIM_MASTER_SLAVE_MODE_ENABLE);
/* Master Mode selection */
TIM_SelectOutputTrig(TIM2, TIM_TRGO_SRC_UPDATE);
/* Slaves Configuration: PWM1 Mode */
TIM_OCInitStructure.OcMode = TIM_OCMODE_PWM1;
TIM_OCInitStructure.OutputState = TIM_OUTPUT_STATE_ENABLE;
TIM_OCInitStructure.Pulse = 1;
TIM_InitOc1(TIM3, &TIM_OCInitStructure);
TIM_InitOc1(TIM4, &TIM_OCInitStructure);
/* Slave Mode selection: TIM3 */
TIM_SelectSlaveMode(TIM3, TIM_SLAVE_MODE_GATED);
TIM_SelectInputTrig(TIM3, TIM_TRIG_SEL_IN_TR1);
/* Select the Master Slave Mode */
TIM_SelectMasterSlaveMode(TIM3, TIM_MASTER_SLAVE_MODE_ENABLE);
/* Master Mode selection: TIM3 */
TIM_SelectOutputTrig(TIM3, TIM_TRGO_SRC_UPDATE);
/* Slave Mode selection: TIM4 */
TIM_SelectSlaveMode(TIM4, TIM_SLAVE_MODE_GATED);
TIM_SelectInputTrig(TIM4, TIM_TRIG_SEL_IN_TR2);
/* TIM enable counter */
TIM_Enable(TIM3, ENABLE);
TIM_Enable(TIM2, ENABLE);
TIM_Enable(TIM4, ENABLE);
代码中大家可以看到,TIM4的触发源选择IR2,TIM3触发源选择IR1,这个是为啥呢?
需要注意看这张表,主从定时器选择都是有对应关系的
然后我们用逻辑分析仪看一下TIM的输出波形
从波形可以看出,由上到下分别是TIM2、TIM3、TIM4输出的PWM,但是为什么TIM2 = 4 TIM3 = 16 TIM4呢?这里指的是频率而非周期
因为TIM3和TIM4的装载值我们都配置的是4-1,即TIM2更新4次后TIM3才更新一次,TIM4对于TIM3也是同理,这样就得到我们现在的波形啦!!
|