STM32f103C8T6定时器用于外部脉冲计数
扫描二维码
随时随地手机看文章
使用STM32f103C8T6作主控制器控制小车,小车的转速由两路光电编码盘输入(左右各一路).利用外部时钟触发模式(TIM——ETRClockMode2Config)计数转数。
第一步,设置GPIO
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_12;//外部脉冲输入端口
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //50M时钟速度
GPIO_Init(GPIOA, &GPIO_InitStructure);
注意:(1)STM32f103C8T6只有TIM1_ETR(PA12,Pin33),和TIM2_CH1_ETR(PA0,Pin10)两个可以用;
(2)外部时钟输入与中断无关;
(3)STM32f103C8T6的这个两个应用中,不需要重映射。
第二步:设置RCC
RCC_ClocksTypeDef RCC_ClockFreq;
SystemInit();//源自system_stm32f10x.c文件,只需要调用此函数,则可完成RCC的配置.
RCC_GetClocksFreq(&RCC_ClockFreq);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
第三步,设置定时器模式
void TIM1_Configuration(void) //只用一个外部脉冲端口
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//配置TIMER1作为计数器
TIM_DeInit(TIM1);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 0x00;
TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); // Time base configuration
TIM_ETRClockMode2Config(TIM1, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0);
TIM_SetCounter(TIM1, 0);
TIM_Cmd(TIM1, ENABLE);
}
void TIM2_Configuration(void) //只用一个外部脉冲端口
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//配置TIMER2作为计数器
TIM_DeInit(TIM2);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 0x00;
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); // Time base configuration
TIM_ETRClockMode2Config(TIM2, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0);
TIM_SetCounter(TIM2, 0);
TIM_Cmd(TIM2, ENABLE);
}
第四步、在主函数中读取计数器的值;
u16 COUN1=0;
u16 COUN2=0;
int main(void)
{
ChipHalInit();
ChipOutHalInit();
while(1)
{
COUN1=TIM1->CNT;
COUN2=TIM2->CNT;
}
}