STM32f103C8T6定時(shí)器用于外部脈沖計(jì)數(shù)
使用STM32f103C8T6作主控制器控制小車,小車的轉(zhuǎn)速由兩路光電編碼盤(pán)輸入(左右各一路).利用外部時(shí)鐘觸發(fā)模式(TIM——ETRClockMode2Config)計(jì)數(shù)轉(zhuǎn)數(shù)。
第一步,設(shè)置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時(shí)鐘速度
GPIO_Init(GPIOA, &GPIO_InitStructure);
注意:(1)STM32f103C8T6只有TIM1_ETR(PA12,Pin33),和TIM2_CH1_ETR(PA0,Pin10)兩個(gè)可以用;
(2)外部時(shí)鐘輸入與中斷無(wú)關(guān);
(3)STM32f103C8T6的這個(gè)兩個(gè)應(yīng)用中,不需要重映射。
第二步:設(shè)置RCC
RCC_ClocksTypeDef RCC_ClockFreq;
SystemInit();//源自system_stm32f10x.c文件,只需要調(diào)用此函數(shù),則可完成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);
第三步,設(shè)置定時(shí)器模式
void TIM1_Configuration(void) //只用一個(gè)外部脈沖端口
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//配置TIMER1作為計(jì)數(shù)器
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) //只用一個(gè)外部脈沖端口
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//配置TIMER2作為計(jì)數(shù)器
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);
}
第四步、在主函數(shù)中讀取計(jì)數(shù)器的值;
u16 COUN1=0;
u16 COUN2=0;
int main(void)
{
ChipHalInit();
ChipOutHalInit();
while(1)
{
COUN1=TIM1->CNT;
COUN2=TIM2->CNT;
}
}