因为一个项目,需要测量单位时间内的一个外部占空比和周期都在变化的脉冲.我的想法是,用第一个定时器A来进行定时一个单位时间,用另一个定时器B来数脉冲数(用输入捕捉,一检测到上升沿就中断一次,并且脉冲数+1).当定时器A的定时的单位时间到时,就用串口输出定时器B数到的脉冲数.然后脉冲数清零.如此下去.
现在就是定时器A能定时一定时间(这个时间不要求精确,几秒就可以),定时器B却实现不了数脉冲数的功能.下面是我写的程序,请大家指点一下哪里有错.我是菜鸟,先谢谢了.用的是STM32F103VCT6
定时器2用于定时几秒并用串口输出脉冲数.(现在串口总是输出0,显示灯能正常闪)
定时器2配置
void tiM2_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 50000;
TIM_TimeBaseStructure.TIM_Prescaler = 1439;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
定时器2中断服务函数
extern s32 Trigger_times;
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
GPIOE->ODR ^= GPIO_Pin_2;//灯闪显示进入了中断
USART_SendData(USART1,Trigger_times);//串口输出脉冲数
while(!USART_GetFlagStatus(USART1,USART_FLAG_TC))
{}
Trigger_times = 0;//脉冲数再清零
}
}
定时器配置,目的是为了检测到脉冲上升沿一次就中断一次
void TIM4_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV2;
TIM_ICInitStructure.TIM_ICFilter = 0x0;
TIM_ICInit(TIM4, &TIM_ICInitStructure);
TIM_Cmd(TIM4, ENABLE);
TIM_ITConfig(TIM4, TIM_IT_CC1, ENABLE);
}
定时器4中断服务函数,目的是每检测到脉冲上升沿时就中断一次并且计数+1,灯闪(程序执行中灯不闪)
void TIM4_IRQHandler(void)
{
if(TIM_GetITStatus(TIM4, TIM_IT_CC1) == SET)
{
TIM_ClearITPendingBit(TIM4, TIM_IT_CC1);
GPIOE->ODR ^= GPIO_Pin_3;
Trigger_times ++;
}
} |