arduino智能超声波避障小车

1.元器件
小车底板,L298N电机驱动模块,arduino板子,两个电机,超声波模块,杜邦线若干(公对公,公对母,母对母都要用到),胶带(用于固定元器件,当然胶水也可以,有螺丝固定最好),5V电池及电池盒(用于板子供电),12V电池及电池盒,用于L298N和电机供电,电烙铁及焊锡丝;
2.安装步骤
(1)硬件连接
用L298N模块的out1,2连接一个电机,out2,3连接剩下一个,然后用12V电源给L298N模块供电,用5V给板子供电,当然用L298N的5V给板子供电也可以,但建议分开供电,然后就是L298N和板子连接,以下是我的连接方式:
ENA:2;ENB:8;
IN3:5;IN1:9;
IN4:6;IN2:10;
每一列控制一个电机;注意连接时要连接在PWM一侧,并且IN1~4连接的端口前要有 ~ 标志,例如 ~ 5,如果没连接到这个上面,电机就不能进行正传及小车后退操作;

然后就是超声波模块连接,将其trag连接到A0端,其为发射端,Echo连接到A1端,为接收端,VCC,GND,连接电源和接地;
以上就是硬件的连接;
(2)代码实现
int i;
int s;

void setup() {
     
  for(i=2;i<=10;i++){
     
    pinMode(i,INPUT);
  }
  pinMode(A1,INPUT);
  pinMode(A0,OUTPUT);
}

void run(int time){
     	//前进函数
  digitalWrite(8,HIGH);//ENBzuo
  digitalWrite(9,HIGH);//IN1
  digitalWrite(10,LOW);//IN2
  analogWrite(9,80);
  analogWrite(10,0);

  digitalWrite(2,HIGH);//ENAyou
  digitalWrite(5,HIGH);//IN3
  digitalWrite(6,LOW);//IN4
  analogWrite(5,80);
  analogWrite(6,0);
  
  delay(time*100);
}

void back(int time){
      //后退
  digitalWrite(8,HIGH);//ENBzuo
  digitalWrite(10,HIGH);//IN1
  digitalWrite(9,LOW);//IN2
  analogWrite(10,80);
  analogWrite(9,0);
  
  
   digitalWrite(2,HIGH);//ENAyou
  digitalWrite(6,HIGH);//IN3
  digitalWrite(5,LOW);//IN4
  analogWrite(6,80);
  analogWrite(5,0);

  delay(time*100);
}
void right(int time){
     	//右转
  digitalWrite(8,HIGH);//ENBzuo
  digitalWrite(9,HIGH);//IN1
  digitalWrite(10,LOW);//IN2
  analogWrite(9,80);
  analogWrite(10,0);

  digitalWrite(2,LOW);//ENA
  digitalWrite(5,LOW);//IN3
  digitalWrite(6,LOW);//IN4
  analogWrite(5,0);
  analogWrite(6,0);
 
  delay(time*100);
}

void left(int time){
     	//左转

  digitalWrite(8,LOW);//ENBzuo
  digitalWrite(9,LOW);//IN1
  digitalWrite(10,LOW);//IN2
  analogWrite(9,0);
  analogWrite(10,0);
  
  digitalWrite(2,HIGH);//ENAyou
  digitalWrite(5,HIGH);//IN3
  digitalWrite(6,LOW);//IN4
  analogWrite(5,80);
  analogWrite(6,0);

  delay(time*100);
}

int distance(){
     		//测距函数
  digitalWrite(A0,LOW);
  delayMicroseconds(2);
  digitalWrite(A0,HIGH);
  delayMicroseconds(15);
  digitalWrite(A0,LOW);
  
  int m = pulseIn(A1,HIGH);
  s=m/58;

  return s;
}

void loop() {
     	//主循环
  s=distance();
  if(s>=50){
     
    run(15);
  }
  else{
     
    back(10);
    right(5);
  }
  //left(15);
}
咋说里,这个代码其实差东西,但条件有限,没有舵机,所有只能判断前方是否有障碍物,因此这里的代码左转是没用的,哈哈,望各位见谅见谅,如果有机会的话,啥时候回补充一下舵机连接和代码。

看到这里,能不能给小友点个赞里。

你可能感兴趣的:(单片机)