i have following code programmed onto arduino uno r3. problem no matter what, chooses turn left. never goes forward, never turns right, never turns around. know leftmotor hooked , working cause if replace if statements in loop command run both motors, both work.
code: [select]
#include <servo.h>
int leftmotor = 2;
int rightmotor = 3;
int leftdistance, rightdistance;
servo pingservo;
long duration;
const int pingpin = 4;
const int dangerdist = 10;
//servo initial position
int pos = 90;
void setup(){
pingservo.attach(5);
pinmode(leftmotor, output);
pinmode(rightmotor, output);
pingservo.write(pos);
}
void loop(){
int distancefwd = ping();
if( distancefwd > dangerdist){
digitalwrite(leftmotor, high);
digitalwrite(rightmotor, high);
}
else{
digitalwrite(leftmotor, low);
digitalwrite(rightmotor, low);
pingservo.write(45);
delay(500);
rightdistance = ping();
delay(500);
pingservo.write(135);
delay(700);
leftdistance = ping();
delay(500);
pingservo.write(pos);
delay(100);
comparedistance();
}
}
void forward(){
digitalwrite(leftmotor, high);
digitalwrite(rightmotor, high);
return;
}
void comparedistance(){
if(leftdistance > rightdistance){
digitalwrite(leftmotor, low);
digitalwrite(rightmotor, high);
delay(1050);
}
else if(rightdistance > leftdistance){
digitalwrite(leftmotor, high);
digitalwrite(rightmotor, low);
delay(1050);
}
else{
digitalwrite(leftmotor, low);
digitalwrite(rightmotor, high);
delay(2100);
}
}
long ping(){
// send out ping))) signal pulse
pinmode(pingpin, output);
digitalwrite(pingpin, low);
delaymicroseconds(2);
digitalwrite(pingpin, high);
delaymicroseconds(5);
digitalwrite(pingpin, low);
//get duration takes receive echo
pinmode(pingpin, input);
duration = pulsein(pingpin, high);
//convert duration distance
return duration / 79 / 2;
}
Arduino Forum > Using Arduino > Programming Questions > Obstacle Avoiding Robot Will Only Turn Left
arduino
Comments
Post a Comment