智能小車開發實作(3)-循跡自走
智能小車開發實作(3)-循跡自走
延伸智能小車開發實作(2)
在小車上新增循跡傳感模組,我所使用的是3路循跡傳感模組
循跡模組概論:
循跡模組又稱tcrt 5000,它是一種紅外反射式光電開關。
TCRT5000由高發射功率紅外光電二極體和高靈敏度光電晶體管組成。
當發射出的紅外線沒有被反射回來或被反射回來但強度不夠大時,
光敏三極體一直處於關斷狀態,此時模塊的輸出端為高電平,
板載指示LED處於熄滅狀態;被檢測物體出現在檢測範圍內時,
紅外線被反射回來且強度足夠大,光敏三極體飽和,模塊輸出低電平,
板載指示LED被點亮。
簡單來說就是當模組的偵測被外物中斷紅外線=低電平
反之,模組沒有偵測外物,紅外線被完整接數=高電平
我們循跡車因為要貼黑色膠布在地板,當模組放於其上,偵測為低電平
時,以此做出對應的動作。
車頭前組裝循跡模組注意事項:
模組感應頭與地面距離約0.5-1cm為佳,在模組板上有個調整靈敏度
的旋鈕,請自行調整。
程式碼:
int E1 = 10; //pwm
int M1 = 12;
int E2 = 11; //pwm
int M2 = 13;
const int irD1=A1;
const int irD2=A2;
const int irD3=A3;
byte IRstatus=0;
//R_speed & L_speed 0~255
void forward(byte R_SPEED, byte L_SPEED)
{
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, HIGH);
digitalWrite(M2, HIGH);
delay(50);
}
void back(byte R_SPEED, byte L_SPEED)
{
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, LOW);
digitalWrite(M2, LOW);
delay(50);
}
void right(byte R_SPEED, byte L_SPEED){
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, HIGH);
digitalWrite(M2, LOW);
delay(50);
}
void left(byte R_SPEED, byte L_SPEED){
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, LOW);
digitalWrite(M2, HIGH);
delay(50);
}
void stop(byte R_SPEED, byte L_SPEED)
{
analogWrite(E1, R_SPEED);
analogWrite(E2, L_SPEED);
digitalWrite(M1, HIGH);
digitalWrite(M2, HIGH);
// delay(50);
}
void driveMotor(byte IRstatus)
{
switch(IRstatus)
{
case 0: //000
stop(0, 0);
delay(50);
forward(80, 80);
Serial.println("forward");
// delay(100);
break;
case 1: //001
stop(0, 0);
delay(50);
left(80, 60);
Serial.println("right");
// delay(100);
break;
case 2: //010
stop(0, 0);
delay(50);
forward(80, 80);
Serial.println("forward");
// delay(100);
break;
case 3: //011
stop(0, 0);
delay(50);
left(80, 60);
Serial.println("right");
// delay(100);
break;
case 4: //100
stop(0, 0);
delay(50);
right(60, 80);
Serial.println("left");
// delay(100);
break;
case 5: //101
stop(0,0);
break;
case 6: //110
stop(0, 0);
delay(50);
right(60, 80);
Serial.println("left");
// delay(100);
break;
case 7: //111
stop(0,0);
break;
}
}
void setup()
{
Serial.begin(9600);
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
pinMode(irD1,INPUT_PULLUP);
pinMode(irD2,INPUT_PULLUP);
pinMode(irD3,INPUT_PULLUP);
}
void loop() {
int val;
IRstatus=0;
val=digitalRead(irD1);
if(val==1){
IRstatus=(IRstatus | (0x01 << 2));
}
val=digitalRead(irD2);
if(val==1){
IRstatus=(IRstatus | (0x01 << 1));
}
val=digitalRead(irD3);
if(val==1){
IRstatus=(IRstatus | 0x01);
}
driveMotor(IRstatus);
}
留言
張貼留言