基于Arduino3路循迹小车

本人西伯利亚蟑螂,最近抽空回顾了一下arduino,顺手做了个arduino循迹小车

(条件所限我的小车为两驱三路循迹模块小车)

话不多说,先上干货。


#define STOP      0
#define FORWARD   1
#define BACKWARD  2
#define TURNLEFT  3
#define TURNRIGHT 4

int leftMotor1 = 14;
int leftMotor2 = 15;
int rightMotor1 = 16;
int rightMotor2 = 17;

int trac1 = 9; //从车头方向的最右边开始排序
int trac2 = 10; 
int trac3 = 11; 
//int trac4 = 12; 

int leftPWM = 5;
int rightPWM = 6;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(leftMotor1, OUTPUT);
  pinMode(leftMotor2, OUTPUT);
  pinMode(rightMotor1, OUTPUT);
  pinMode(rightMotor2, OUTPUT);
  pinMode(leftPWM, OUTPUT);
  pinMode(rightPWM, OUTPUT);
  //寻迹模块D0引脚初始化
  pinMode(trac1, INPUT);
  pinMode(trac2, INPUT);
  pinMode(trac3, INPUT);
  //pinMode(trac4, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  tracing();


}
void motorRun(int cmd,int value)
{
  analogWrite(leftPWM, value);  //设置PWM输出,即设置速度
  analogWrite(rightPWM, value);
  switch(cmd){
    case FORWARD:
      Serial.println("FORWARD"); //输出状态
      digitalWrite(leftMotor1, HIGH);
      digitalWrite(leftMotor2, LOW);
      digitalWrite(rightMotor1, HIGH);
      digitalWrite(rightMotor2, LOW);
      break;
     case BACKWARD:
      Serial.println("BACKWARD"); //输出状态
      digitalWrite(leftMotor1, LOW);
      digitalWrite(leftMotor2, HIGH);
      digitalWrite(rightMotor1, LOW);
      digitalWrite(rightMotor2, HIGH);
      break;
     case TURNLEFT:
      Serial.println("TURN  LEFT"); //输出状态
      digitalWrite(leftMotor1, HIGH);
      digitalWrite(leftMotor2, LOW);
      digitalWrite(rightMotor1, LOW);
      digitalWrite(rightMotor2, HIGH);
      break;
     case TURNRIGHT:
      Serial.println("TURN  RIGHT"); //输出状态
      digitalWrite(leftMotor1, LOW);
      digitalWrite(leftMotor2, HIGH);
      digitalWrite(rightMotor1, HIGH);
      digitalWrite(rightMotor2, LOW);
      break;
     default:
      Serial.println("STOP"); //输出状态
      digitalWrite(leftMotor1, LOW);
      digitalWrite(leftMotor2, LOW);
      digitalWrite(rightMotor1, LOW);
      digitalWrite(rightMotor2, LOW);
  }
}
void tracing()
{
  int data[3];
  data[0] = digitalRead(9);
  data[1] = digitalRead(10);
  data[2] = digitalRead(11);
 // data[3] = digitalRead(12);

  if(!data[0]&&!data[1]&&!data[2])//左右都没有检测到黑线
  {
    motorRun(FORWARD,115);
  }

  if(data[0]||data[1])  //右边检测到黑线
  {
    motorRun(TURNLEFT,120);
  }

  if(data[2])  //左边检测到黑线
  {
    motorRun(TURNRIGHT,120);
  }

  if(data[0]&&data[2])  //左右都检测到黑线是停止
  {
    motorRun(STOP,0);
    while(1);
  }

  Serial.print(data[0]);
  Serial.print("---");
  Serial.print(data[1]);
  Serial.print("---");
  Serial.print(data[2]);
  Serial.print("---");
 // Serial.println(data[3]);
}

循迹的原理是依靠各个循迹模块对应的引脚上返回电平的高低,来判断是否触碰到黑线。根据判断是哪个位置模块触碰黑线,做出相应执行动作。循迹的转弯主要依靠pwm+正反转,(个人觉得这种方式最方便)。PWM原理有疑惑的地方,请自行百度。

希望对各位朋友有帮助。

我是蟑螂,再见。

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页