|
const byte echo_pin = 12;
const byte trig_pin = 13;
const byte rangingLeft_pin = 7;
const byte rangingRight_pin = 8;
const byte inPin_leftB = 6;
const byte inPin_leftA = 9;
const byte inPin_rightA = 3;
const byte inPin_rightB = 5;
int distan;
byte rangingA;
byte rangingB;
void setup() {
pinMode(echo_pin,INPUT);
pinMode(trig_pin,OUTPUT);
pinMode(rangingLeft_pin,INPUT);
pinMode(rangingRight_pin,INPUT);
pinMode(inPin_leftA,OUTPUT);
pinMode(inPin_leftB,OUTPUT);
pinMode(inPin_rightA,OUTPUT);
pinMode(inPin_rightB,OUTPUT);
}
int getDistance(){
int dist;
digitalWrite(trig_pin,LOW);
delayMicroseconds(2);
digitalWrite(trig_pin,HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin,LOW);
dist=pulseIn(echo_pin,HIGH)/58;
return dist;
}
void goUp(int up_speed)
{
analogWrite(inPin_leftA,0);
analogWrite(inPin_rightA,0);
analogWrite(inPin_leftB,up_speed);
analogWrite(inPin_rightB,up_speed);
}
void goLeft(int left_speed)
{
analogWrite(inPin_leftA,left_speed);
analogWrite(inPin_rightB,left_speed);
analogWrite(inPin_leftB,255);
analogWrite(inPin_rightA,255);
}
void goRight(int right_speed)
{
analogWrite(inPin_leftB,right_speed);
analogWrite(inPin_rightA,right_speed);
analogWrite(inPin_leftA,255);
analogWrite(inPin_rightB,255);
}
void goBack(int back_speed)
{
analogWrite(inPin_leftB,back_speed);
analogWrite(inPin_rightB,back_speed);
analogWrite(inPin_leftA,255);
analogWrite(inPin_rightA,255);
}
void goStop()
{
analogWrite(inPin_leftA,0);
analogWrite(inPin_leftB,0);
analogWrite(inPin_rightA,0);
analogWrite(inPin_rightB,0);
}
void loop(){
distan = getDistance();
rangingA = digitalRead(rangingLeft_pin);
rangingB = digitalRead(rangingRight_pin);
if(distan >= 2 && distan <= 10 && rangingA == 0 && rangingB == 0)
{
goUp(100);
}
else if(distan >= 2 && distan <= 10 && rangingA == 1 && rangingB == 0)
{
goRight(100);
delay(100);
goStop();
}
else if(distan >= 2 && distan <= 10 && rangingA == 0 && rangingB == 1)
{
goLeft(100);
delay(100);
goStop();
}
}
是的,我复制了,开著車子,它只在原地轉,可能是你所說的PIN 位不對,這个程序你是否用Altar小车原裝电机驱动 及 馬達測試? 因為之前聽你說過有些pin 位 有衝突, 因此現在有些PIN位都改了, 超聲波接D12 & D13 ,舵機接D3, 紅外線循跡接D2 & D4, 左車頭的紅外線感應接A0, 右車頭的紅外線感應接D8, 紅外線接收模塊D11, 电机驱动模塊接D5,D6,D9,D10, 這樣有問題嗎? 請師兄指點小弟。 |
|