This is my code for moving an activity bot from its starting point to the ending point. It detects obstacles on both sides and turns away from them.
I save the sequence of moves in an array so that I can return to the starting point without using any sensors. **(Which is the code after the "//return" comment)
#include "simpletools.h"
#include "abdrive.h"
#include "ping.h"
int back[200];
int i = 0;
int main() {
int distance;
int irLeft = 0, irRight = 0;
low(26);
low(27);
while (1) {
if (ping_cm(8) < 5) {
break;
}
freqout(11, 1, 38000);
irLeft = input(10);
freqout(1, 1, 38000);
irRight = input(2);
if (irLeft == irRight == 1) {
drive_goto(10,10);
back[i] = 10;
++i;
back[i]= 10;
++i;
}
if (irLeft == 0) {
drive_goto(20,10);
back[i] = 20;
++i;
back[i] = 10;
++i;
}
if (irRight == 0) {
drive_goto(10,20);
back[i]= 10;
++i;
back[i]= 20;
++i;
}
}
drive_goto(51, 0); // Make a 180 degree turn
drive_goto(51, 0);
//return
while (1) {
if (i == 0) {
break;
}
drive_goto(back[i], back[--i]);
--i;
}
return 0;
}
The robot successfully moves to the goal, but it does not move back to the starting point. What can the problem be?
You appear to have an off-by-one error. As you move forward, you track in variable i
the index of the next available position in your movement history array. When you start the trip back, you use the current value of i
as if it were instead the index of the last value recorded. On the way back you need to decrement i
before each read, mirroring the behavior on the forward path of incrementing it after each write.