STM32计数器配置
扫描二维码
随时随地手机看文章
void Counter_Config()
{
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//TIM4输出初始化
TIM_DeInit(TIM4);
TIM_TimeBaseStructure.TIM_Period = 100; //计数值=100-1
TIM_TimeBaseStructure.TIM_Prescaler = 0; //预分频
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Down; //模式
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); //基本初始化
TIM_SetCounter(TIM4, 100); //设置 TIM4 计数器寄存器值//设置 TIMx 自动重装载寄存器值
TIM_ARRPreloadConfig(TIM4, ENABLE);
TIM_SelectInputTrigger(TIM4, TIM_TS_TI2FP2); //若为通道1 ,则为TIM_TS_TI1FP1
TIM_SelectSlaveMode(TIM4,TIM_SlaveMode_External1);
TIM_SetCompare2(TIM4, 100);
TIM_SetComper1(TIM4,100);TIM_Cmd(TIM4, ENABLE); //启动TIM4TIM_ClearFlag(TIM4, TIM_IT_CC2);
TIM_ITConfig(TIM4, TIM_IT_CC2, ENABLE)//中断配置
NVIC_InitStructure.NVIC_IRQChannel =TIM4_IRQChannel;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3; //抢占优先级0NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //响应优先级0NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //允许中断
NVIC_Init(&NVIC_InitStructure); //写入设置
}
void TIM4_IRQHandler(void)
{
TIM_ClearFlag(TIM4, TIM_IT_CC2);
XX++;
}