(智能小车)STM32+L298N+光电/霍尔传感器+串口/OLED屏测速,测速值通过IIC可以显示到OLED,亲测。(程序代码注释详细)_m0_54195456的博客-CSDN博客
光电传感器有遮挡时,输出高电平;无遮挡,输出低电平。我们接受到一次低电平时,把这个脉冲加一,轮子上有编码圈一圈可以让脉冲累加20次。我用了2个定时器和两个外部中断,定时器分别用来仿PWM输出和定时,外部中断分别用来光电传感器的输出(输出的高低电平会输入到单片机的IO口)和按键输入控制电机转动。现在PWM输出暂时可以不用管。定时器定时1ms秒,检测是否接受到传感器输入脉冲,计时1S后将脉冲累计的值(该值设为num)num/20返回我们的结果为每秒轮子所转的圈数。将该结果每秒的转速显示到OLED上,当然,也可以自己稍微修改代码用串口输出并显示。
下面来看测速用到的几个代码段
//触发传感器输入 void INIT_GD(void) //Key0 { GPIO_InitTypeDef GPIO_InitStruct; //结构体 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //时钟GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPD; //下拉GPIO_Init(GPIOB, &GPIO_InitStruct);}
//定时器4void TIM4_inIt(void){//结构体TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;NVIC_InitTypeDef NVIC_InitStructure; //时钟RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //配置中断NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn; //TIM3通道NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //子优先级NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //使能NVIC_Init(&NVIC_InitStructure); //配置TIM_TimeBaseStructure.TIM_Period = 999; //重装载寄存器TIM_TimeBaseStructure.TIM_Prescaler =71; //预分频TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM4向上计数TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); //配置 TIM4TIM_Cmd(TIM4, ENABLE); //使能TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE ); //开启定时器4,
//进入一次中断1Msvoid TIM4_IRQHandler(void) {if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET) //1ms{TIM_ClearITPendingBit(TIM4, TIM_IT_Update );time++; //测每秒的转速,每一秒更新一次if(Key0 == 1)flag=1;if(Key0==0 && flag==1){flag=0; //清除标志num=num+1; //传感器触发次数}if(time == 1000) //计时1S,计算转速{Circle=num/20; //转速time=0; num=0; } }}
详细代码链智能小车基于STM32的测速,亲测https://blog.csdn.net/m0_54195456/article/details/121042194
文章评论