Arduino 避障车 (部分代码)

1.实现小车的前进后退

void setup() {
 // put your setup code here, to run once:
   pinMode(10 , OUTPUT);
   pinMode(6 , OUTPUT);
   pinMode(5 , OUTPUT);
   pinMode(9 , OUTPUT);
}
void loop(){
 // put your main code here, to run repeatedly: 

  digitalWrite(5,HIGH);
  digitalWrite(6,LOW);
  digitalWrite(9,HIGH);
  digitalWrite(10,LOW);
  delay(1000);   
  digitalWrite(5,LOW);
  digitalWrite(6,HIGH);
  digitalWrite(9,LOW);
  digitalWrite(10,HIGH);
  delay(1000);   
}

2.实现近红外基础功能

void setup() {
  // put your setup code here, to run once:
   pinMode(10 , OUTPUT);
   pinMode(6 , OUTPUT);
   pinMode(5 , OUTPUT);
   pinMode(9 , OUTPUT);
   pinMode(14,INPUT);
}
void loop() {
  // put your main code here, to run repeatedly: 
  int a = digitalRead(14);
  if(a == 1)
  {
  digitalWrite(5,LOW);
  digitalWrite(6,HIGH);
  digitalWrite(9,LOW);
  digitalWrite(10,HIGH);
  delay(1000);
  }
  else{
  digitalWrite(5,HIGH);
  digitalWrite(6,LOW);
  digitalWrite(9,HIGH);         
  digitalWrite(10,LOW);   
 }
}

 

3.小车避障:

void setup() {
// put your setup code here, to run once
    //外红外传感器 
   pinMode(14,INPUT);   //A0 端口
   pinMode(18,INPUT);   //A4 端口
   // (5,6) ; (9,10)
   pinMode(5,OUTPUT);
   pinMode(6,OUTPUT);
   pinMode(9,OUTPUT);
   pinMode(10,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly: 
  //获取信号的状态; 1是高电平,0是低电平
  int a=digitalRead(14);      //A0
  int b=digitalRead(18);      //A4
  //LOW是触发,在这里是遇到墙壁的意思
  if(a== LOW && b==LOW)
  {
      turnback();
      delay(100);
      turnright();
      delay(100);
      forward();
   }
   else if(a== HIGH && b== LOW)
   {
      turnleft();
      delay(100);
      forward();
    }
    else if(a== LOW && b==HIGH)
    {
       turnright();
       delay(100);
       forward();
     }
     else if(a==HIGH && b==HIGH)
     {
         forward();
     }
}
void turnright()        //right
{
   digitalWrite(5,LOW);
   digitalWrite(6,LOW);
   digitalWrite(9,HIGH);
   digitalWrite(10,LOW);
}
void turnleft()        //left
{
   digitalWrite(5,HIGH);
   digitalWrite(6,LOW);
   digitalWrite(9,LOW);
   digitalWrite(10,LOW);
}

void turnback()        //back
{
    digitalWrite(5,LOW);
    digitalWrite(6,HIGH);
    digitalWrite(9,LOW);
    digitalWrite(10,HIGH);
}

void forward()        //strght
{
    digitalWrite(5,HIGH);
    digitalWrite(6,LOW);
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW);
}
相关文章
相关标签/搜索