最近在做小车,需要对小车进行测速,用到的是测速码盘和光电对管,基本的原理百度了一下,解释为“模块槽中无遮挡时,接收管导通,模块 OUT 输出低电平,遮挡时,OUT 输出高电平”。感觉应该用输入捕获功能来统计时间内的上升沿次数来计算方波个数,进而求得电机的转速,自己尝试了一下,程序是开启TIM5 通道1 对应PA0 ,将模块的OUT插在PA0上,可是出现了很多问题,比如只要在PA0上插上一根杜邦线,另一头不连接任何东西,就会传出来速度。当把模块连接上时,串口显示的数据就会在0——12之间来回变化等等,求论坛的大神帮小白看一下程序或者麻烦提供思路,谢谢大家了!
附录程序:
TIM_ICInitTypeDef TIM5_ICInitStructure;
void TIM5_Cap_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode =GPIO_Mode_IPD ;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// psc 7199 arr 99999
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler =psc;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);
TIM5_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM5_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //上升沿捕获
TIM5_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM5_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM5_ICInitStructure.TIM_ICFilter = 0x00;
TIM_ICInit(TIM5, &TIM5_ICInitStructure);
NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ITConfig(TIM5,TIM_IT_CC1,ENABLE);
TIM_Cmd(TIM5,ENABLE );
}
u8 a=0;
void TIM5_IRQHandler(void)
{
if (TIM_GetITStatus(TIM5, TIM_IT_CC1) != RESET)
a++;
}
主程序
int main(void)
{
u32 n=0; //转速
u32 dushu=0;
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
uart_init(115200);
TIM5_Cap_Init(99999,7199);
while(1)
{
delay_ms(10);
MotorDriver_L_Forward();//左轮直行
dushu=a*18;
n=dushu/360;
printf("SPEED:%d
",n);
}
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>