D. the main loop(s) – Pololu 3pi Robot User Manual

Page 32

Advertising
background image

that on the way, since you’ll travel down every hallway exactly twice. We use this simple, reliable strategy in our 3pi
maze solving example:

// This function decides which way to turn during the learning phase of

// maze solving. It uses the variables found_left, found_straight, and

// found_right, which indicate whether there is an exit in each of the

// three directions, applying the "left hand on the wall" strategy.

char select_turn(unsigned char found_left, unsigned char found_straight,

unsigned char found_right)

{

// Make a decision about how to turn. The following code

// implements a left-hand-on-the-wall strategy, where we always

// turn as far to the left as possible.

if(found_left)

return 'L';

else if(found_straight)

return 'S';

else if(found_right)

return 'R';

else

return 'B';

}

The values returned by select_turn() correspond to the values used by turn(), so these functions will work nicely
together in our main loop.

8.d. The Main Loop(s)

The strategy of our program is expressed in the file

maze-solve.c

. Most importantly, we want to keep track of the

path that we have followed, so we define an array storing up to 100; these will be the same characters used in the
turn() function. We also need to keep track of the current path length so that we know where to put the characters in
the array.

char path[100] = "";

unsigned char path_length = 0; // the length of the path

Our “main loop” is found in the function maze_solve(), which is called after calibration, from

main.c

. This function

actually includes two main loops – a first one that handles solving the maze, and a second that replays the solution for
the fastest possible time. In fact, the second loop is actually a loop within a loop, since we want to be able to replay
the solution many times. Here’s an outline of the code:

// This function is called once, from main.c.

void maze_solve()

{

while(1)

{

// FIRST MAIN LOOP BODY

// (when we find the goal, we use break; to get out of this)

}

// Now enter an infinite loop - we can re-run the maze as many

// times as we want to.

while(1)

{

// Beep to show that we finished the maze.

// Wait for the user to press a button...

int i;

for(i=0;i<path_length;i++)

{

// SECOND MAIN LOOP BODY

}

// Follow the last segment up to the finish.

follow_segment();

// Now we should be at the finish! Restart the loop.

Pololu 3pi Robot User's Guide

© 2001–2014 Pololu Corporation

8. Example Project #2: Maze Solving

Page 32 of 63

Advertising