按文档的例子和其它例子都很少使用timer1的,不知道为什么,但是我想使用它,方便端口重用,我一开始使用tim1 ch3,死活不工作,搞了几天,没有办法换了一个ch2, 结果同样的代码就工作了。不知道为什么,希望看到的高手告知。
分享PPM的代码如下,是捕捉航模的PPM信号。
#define NUM_CHANNELS 8
int cur_ch = 0;
void InitPPMCapture()
{
GPIO_InitTypeDef GPIO_InitStructure={0};
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure={0};
TIM_ICInitTypeDef TIM_ICInitStru={0};
NVIC_InitTypeDef NVIC_InitStructure={0};
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_2); //PA9 - TIM1_CH2
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_2); //PA10 - TIM1_CH3
//
//FOR PPM
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF; //ppm 22ms
TIM_TimeBaseStructure.TIM_Prescaler = 47; // 48mhz / (47+1) 1 us
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); //ppm 22ms
TIM_ARRPreloadConfig(TIM1,DISABLE);
TIM_ICInitStru.TIM_Channel = TIM_Channel_2; //CC2S=01 选择输入端 IC2映射到TI2上
TIM_ICInitStru.TIM_ICPolarity = TIM_ICPolarity_Rising; //上升沿捕获
TIM_ICInitStru.TIM_ICSelection = TIM_ICSelection_DirectTI; //映射到TI2上
TIM_ICInitStru.TIM_ICPrescaler = TIM_ICPSC_DIV1; //配置输入分频,不分频
TIM_ICInitStru.TIM_ICFilter = 0x00;//IC1F=0000 配置输入滤波器 不滤波
TIM_ICInit(TIM1, &TIM_ICInitStru);
TIM_InternalClockConfig(TIM1);
TIM_SelectMasterSlaveMode(TIM1,TIM_MasterSlaveMode_Disable);
TIM_SelectSlaveMode(TIM1,TIM_SlaveMode_Reset);
//TIM_SelectInputTrigger(TIM1,TIM_TS_TI2FP2);
NVIC_InitStructure.NVIC_IRQChannel = TIM1_CC_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM1,ENABLE); //使能定时器1
TIM_ITConfig(TIM1, TIM_IT_CC2,ENABLE);
TIM_CCxCmd(TIM1,TIM_Channel_2,TIM_CCx_Enable);
TIM_Cmd(TIM1,ENABLE); //使能定时器1
}
void TIM1_CC_IRQHandler(void)
{
if (TIM_GetITStatus(TIM1, TIM_IT_CC2) != RESET)
{
uint16_t val =TIM_GetCapture2(TIM1);
TIM_SetCounter(TIM1, 0);
if (val > 3000) {
// sync signal
cur_ch = 0;
}
else if(val > 500)
{
rx_current_state = BINDED_GOT_RC_DATA;
last_recv_signal_time = GetTickCount();
if (cur_ch < NUM_CHANNELS) {
Channel_Output[cur_ch] = val;
cur_ch++;
}
else
{
cur_ch = 0;
}
}
/* over-capture */
if (TIM_GetFlagStatus(TIM1, TIM_FLAG_CC2OF) != RESET)
{
TIM_ClearFlag(TIM1, TIM_FLAG_CC2OF);
}
}
}