|
const byte echo_pin = 12;
const byte trig_pin = 13;
const byte rangingLeft_pin = A0;
const byte rangingRight_pin = 8;
const byte inPin_leftB = 5;
const byte inPin_leftA = 6;
const byte inPin_rightA = 9;
const byte inPin_rightB = 10;
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 == 0 && rangingB == 1)
{
goRight(100);
delay(100);
goStop();
}
else if(distan >= 2 && distan <= 10 && rangingA == 1 && rangingB == 0)
{
goLeft(100);
delay(100);
goStop();
}
else
{
goStop();
}
}
我上傳了你給的這個,可惜沒有任何反應,你上傳是否可運行? |
|