int MotorRight1=14; int MotorRight2=15; int MotorLeft1=16; int MotorLeft2=17; int MotorRPWM=3; int MotorLPWM=5; const int SensorLeft = 2; //左感测器輸入腳 //const int SensorMiddle= 4 ; //中感测器輸入腳 const int SensorRight = 6; //右感测器輸入腳 int SL; //左感测器狀態 //int SM; //中感测器狀態 int SR; //右感测器狀態 void setup() { Serial.begin(9600); pinMode(MotorRight1, OUTPUT); // 腳位 14 (PWM) pinMode(MotorRight2, OUTPUT); // 腳位 15 (PWM) pinMode(MotorLeft1, OUTPUT); // 腳位 16 (PWM) pinMode(MotorLeft2, OUTPUT); // 腳位 17 (PWM) pinMode(MotorLPWM, OUTPUT); // 腳位 3 (PWM) pinMode(MotorRPWM, OUTPUT); // 腳位 5 (PWM) pinMode(SensorLeft, INPUT); //定義左感测器 // pinMode(SensorMiddle, INPUT);//定義中感测器 pinMode(SensorRight, INPUT); //定義右感测器 } void loop() { SL = digitalRead(SensorLeft); // SM = digitalRead(SensorMiddle); 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);; }}}
时间: 2024-10-15 01:03:02