我这边使用的是STM32F103R8T6。设定主定时器为TIM4,从定时器为TIM3,由TIM4发送PWM,当TIM4的PWM溢出时,会进入TIM3的update中断,此时将TIM4的计数值清空,这样只要每次清空之前设定一下下一次PWM的计数值就可以做到对TIM4的脉冲精确计数了。
代码如下:
//TIM4主模式
void TIM4_config(u32 Cycle)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB , ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; //TIM2_CH2 PB7
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = Cycle-1;
TIM_TimeBaseStructure.TIM_Prescaler = 48; //设置用来作为TIMx时钟频率除数的预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS= Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_Pulse = (Cycle + 1)/2; //设置待装入捕获寄存器的脉冲值
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性
TIM_OC2Init(TIM4, &TIM_OCInitStructure);
TIM_SelectMasterSlaveMode(TIM4, TIM_MasterSlaveMode_Enable);
TIM_SelectOutputTrigger(TIM4, TIM_TRGOSource_Update);
TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM4, ENABLE);
}
//TIM3从模式
void TIM3_config(u32 PulseNum)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Period = PulseNum-1;
TIM_TimeBaseStructure.TIM_Prescaler =0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_SelectInputTrigger(TIM3, TIM_TS_ITR3);
//TIM_InternalClockConfig(TIM3);
TIM3->SMCR|=0x37; //设置从模式寄存器
//TIM_ARRPreloadConfig(TIM3, ENABLE);
TIM_ITConfig(TIM3,TIM_IT_Update,DISABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_3);
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void Pulse_output(u32 Cycle,u32 PulseNum)
{
TIM3_config(PulseNum);
TIM_Cmd(TIM3, ENABLE);
TIM_ClearITPendingBit(TIM3,TIM_IT_Update);
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE);
TIM4_config(Cycle);
TIM_Cmd(TIM4, ENABLE);
}
int main(void)
{
Pulse_output(1000,2000); //发出1000Hz的脉冲,计数到2000个的时候就进入一次TIM3的Update
while(1)
{
}
}
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
//可以在这里写个IO翻转即可看到效果
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
}
}
具体的参数还需各位同学按照自己的环境小调一下,我这边主频是48Mhz的
需要注意的是,若需要移植到其它定时器,请翻阅数据手册,找到SMCR寄存器的使用说明,并且注意它的赋值更改。
|