int leftMotor1 =8;
int leftMotor2 =7;
int rightMotor1 =2;
int rightMotor2 =4;
int leftPWM=6;
int rightPWM=5;
int trac1 = 10; //从车头方向的最右边开始排序
int trac2 = 11;
int trac3 = 12;
int trac4 = 13;
int LeftValue1;
int LeftValue2;
int RightValue1;
int RightValue2;
void setup() {
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 run(int left_speed, int right_speed)
{
//左电机前进
digitalWrite(leftMotor1, HIGH); //左电机前进使能
digitalWrite(leftMotor2, LOW); //左电机后退禁止
analogWrite(leftPWM,left_speed);
//右电机前进
digitalWrite(rightMotor1, HIGH); //右电机前进使能
digitalWrite(rightMotor2, LOW); //右电机后退禁止
analogWrite(rightPWM,right_speed);
}
void brake(int time)
{
digitalWrite(leftMotor1, LOW);
digitalWrite(leftMotor2, LOW);
digitalWrite(rightMotor1, LOW);
digitalWrite(rightMotor2, LOW);
delay(time * 50);
}
void left(int left_speed, int right_speed)
{
//左电机停止
digitalWrite(leftMotor1, LOW); //左电机前进禁止
digitalWrite(leftMotor2, LOW); //左电机后退禁止
analogWrite(leftPWM, left_speed);
//右电机前进
digitalWrite(rightMotor1, HIGH); //右电机前进使能
digitalWrite(rightMotor2, LOW); //右电机后退禁止
analogWrite(rightPWM, right_speed);
}
void right(int left_speed, int right_speed)
{
//左电机前进
digitalWrite(leftMotor1, HIGH); //左电机前进使能
digitalWrite(leftMotor2, LOW); //左电机后退禁止
analogWrite(leftPWM, left_speed);
//右电机停止
digitalWrite(rightMotor1, LOW); //右电机前进禁止
digitalWrite(rightMotor2, LOW); //右电机后退禁止
analogWrite(rightPWM, right_speed);
}
//检测到黑线时循迹模块相应的指示灯亮,端口电平为LOW
//未检测到黑线时循迹模块相应的指示灯灭,端口电平为HIGH
void loop()
{
LeftValue1 = digitalRead(trac1);
LeftValue2 = digitalRead(trac2);
RightValue1 = digitalRead(trac3);
RightValue2 = digitalRead(trac4);
if(LeftValue1 == HIGH && LeftValue2 ==HIGH && RightValue1 == HIGH && RightValue1 == HIGH)//1 1 1 1
{
run(120, 120);
}
else if(LeftValue1 == LOW && LeftValue2 ==LOW && RightValue1 == LOW && RightValue1 == LOW)//0 0 0 0
{
run(100,100);
}
else if(LeftValue1 == HIGH && LeftValue2 ==HIGH && RightValue1 == LOW && RightValue1 == HIGH)//1 1 0 1
{
right(50,30);
}
else if(LeftValue1 == HIGH && LeftValue2 ==HIGH && RightValue1 == LOW && RightValue1 == LOW)//1 1 0 0
{
right(30,0);
delay(50);
}
}