stm32定时器接力
cortex-M3的定时器只有16位,有时候计数大于16位时,用两个定时器组成32位就非常有用了,甚至可用4个接到64位的计数。
下面这代码,是在编码器2模式下,对编码器进行计数,TIM4为低16位计数器,TIM4溢出一次TIM3就加1,TIM3设置2次就溢出了。keil这东西对中文的支持太差了,注释复制过来全不能看了,不过也简单,这只是给出定时器的配置,想要中断的,还要配下中断。
void TIM4_External_Clock_CountingMode(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
/*配置接编码器的引脚*/
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOD, &GPIO_InitStructure);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
TIM_DeInit(TIM4);
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = 0x00;
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit( TIM4, &TIM_TimeBaseStructure); // Time base configuration
TIM_EncoderInterfaceConfig(TIM4, TIM_EncoderMode_TI12,TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);//编码器模式配置
TIM_SelectMasterSlaveMode(TIM4, TIM_MasterSlaveMode_Enable);//TIM4设置成主模式,这个不能少
TIM_SelectOutputTrigger(TIM4,TIM_TRGOSource_Update);//这个很重要,设置TIM4溢出时,产生更新事件,下面的TIM3就是用这个更新事件作为时钟源的
TIM_ClearFlag(TIM4, TIM_FLAG_Update);//
TIM4->DIER|=1<<0; //允许中断
TIM4->DIER|=1<<6; //使能中断
TIM4->CNT=0;
TIM_Cmd(TIM4,DISABLE);
}
void TIM4_to_TIM3(void)//
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_DeInit(TIM3);//
TIM_ITRxExternalClockConfig(TIM3, TIM_TS_ITR3);//选择TIM4作为触发源
TIM_TimeBaseStructure.TIM_Prescaler =0;//
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;//
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;//
TIM_TimeBaseStructure.TIM_Period =2-1;//
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);
TIM_SelectSlaveMode(TIM3,TIM_SlaveMode_Gated);//作为从模式,被动触发嘛
TIM_SetCounter(TIM3,0);
TIM_ClearFlag(TIM3,TIM_FLAG_Update);//
TIM_ARRPreloadConfig(TIM3,DISABLE);//
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE);//
TIM_Cmd(TIM3,ENABLE);
}
posted on 2015-06-21 00:01 come_on_hands 阅读(347) 评论(0) 编辑 收藏 举报