arduino 循迹小车

大家好,今天我们来做一个光杆寻黑线的实验。即小车循着黑色的赛道走,不会脱离轨道,很神奇吧?下面是小编的一段代码。

int MotorRight1 = 14;
int MotorRight2 = 15;
int MotorLeft1 = 16;
int MotorLeft2 = 17;
int MotorRPWM = 3;
int MotorLPWM = 5;
const int SensorLeft = 2;
const int SensorRight = 6;
int SL;
int SR;

void setup() {
  Serial.begin(9600);
  pinMode(MotorRight1, OUTPUT);
  pinMode(MotorRight2, OUTPUT);
  pinMode(MotorLeft1,  OUTPUT);
  pinMode(MotorLeft2,  OUTPUT);
  pinMode(MotorLPWM,  OUTPUT);
  pinMode(MotorRPWM,  OUTPUT);
  pinMode(SensorLeft, INPUT);
  pinMode(SensorRight, INPUT)
}

void loop() {
  SL = digitalRead(SensorLeft);
  SR = digitalRead(SensorRight);
  if (SL == LOW && SR == LOW) {
    digitalWrite(MotorRight1, HIGH);
    digitalWrite(MotorRight2, LOW);
    analogWrite(MotorRPWM, 150);
    digitalWrite(MotorLeft1, HIGH);
    digitalWrite(MotorLeft2, LOW);
    analogWrite(MotorLPWM, 150);
  }
  else {
    if (SL == HIGH & SR == LOW) {
      delay(1);
      digitalWrite(MotorRight1, HIGH);
      digitalWrite(MotorRight2, LOW);
      analogWrite(MotorRPWM, 130);
      digitalWrite(MotorLeft1, LOW);
      digitalWrite(MotorLeft2, LOW);
    }
    else if (SR == HIGH & SL == LOW) {
      delay(1);
      digitalWrite(MotorRight1, LOW);
      digitalWrite(MotorRight2, LOW);
      digitalWrite(MotorLeft1, HIGH);
      digitalWrite(MotorLeft2, LOW);
      analogWrite(MotorLPWM, 130);
    }
   else {
      digitalWrite(MotorRight1, LOW);
      digitalWrite(MotorRight2, LOW);
      digitalWrite(MotorLeft1, LOW);
      digitalWrite(MotorLeft2, LOW);;
    }
  }
}

上传代码后,小车就会沿着黑色的轨道走了。

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