超声波避障小车原理就是通过给超声波模块超过10us的高电平信号,自动发送8个40KHZ的方波,来检测是不是有信号的返回,如果有信号的返回,那么就判断为前方有障碍物,并且通过舵机云台,来实现180度的旋转,检测左右两边是否的有障碍物,从而进行避障的功能。
说完原理,接下来就是根据各部件的原理来进行编程,我的超声波避障小车主要涉及了超声波HC-SR04模块,L298N电机驱动模块,舵机sg90模块。
首先是最基本的电机驱动模块的相关代码:
#include "bsp_motor.h"
#include "delay.h"
#include <math.h>
void TIM4_PWM_Motor(unsigned int arr,unsigned int psc)
{
GPIO_InitTypeDef GPIO_InitStuct;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStuct;
TIM_OCInitTypeDef TIM_OCInitStuct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStuct.GPIO_Pin=GPIO_Pin_7; //左电机控制
GPIO_InitStuct.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStuct.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStuct);
GPIO_InitStuct.GPIO_Pin=GPIO_Pin_8; //左电机PWM
GPIO_InitStuct.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStuct.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStuct);
GPIO_InitStuct.GPIO_Pin=GPIO_Pin_9; //右电机PWM
GPIO_InitStuct.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStuct.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStuct);
GPIO_InitStuct.GPIO_Pin=GPIO_Pin_4; //右电机方向控制
GPIO_InitStuct.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStuct.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStuct);
TIM_TimeBaseInitStuct.TIM_ClockDivision=0;
TIM_TimeBaseInitStuct.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStuct.TIM_Period=arr;
TIM_TimeBaseInitStuct.TIM_Prescaler=psc;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStuct);
TIM_OCInitStuct.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStuct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStuct.TIM_Pulse = 0;
TIM_OCInitStuct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC3Init(TIM4, &TIM_OCInitStuct);
TIM_OC4Init(TIM4, &TIM_OCInitStuct);
TIM_CtrlPWMOutputs(TIM4,ENABLE);
TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable);
TIM_OC4PreloadConfig(TIM4, TIM_OCPreload_Enable);
TIM_Cmd(TIM4, ENABLE);
}
void car_run(unsigned char ucChannel,signed char cSpeed)
{
short PWM;
PWM = 7201 - fabs(cSpeed)*72;
switch(ucChannel)
{
case 0://右轮
TIM_SetCompare3(TIM4,PWM);
if (cSpeed>0)
GPIO_ResetBits(GPIOA,GPIO_Pin_4);
else if(cSpeed<0)
GPIO_SetBits