15 Maze Exploration
Program 15.1: Explore-Left
1void explore_left(int goal_x, int goal_y)
2{ int x=0, y=0, dir=0; /* start position */
3int front_open, left_open, right_open;
4
5while (!(x==goal_x && y==goal_y)) /* goal not reached */
6{ front_open = PSDGet(psd_front) > THRES;
7 |
left_open = PSDGet(psd_left) |
> THRES; |
|
8 |
right_open = PSDGet(psd_right) |
> THRES; |
|
9 |
if (left_open) turn(+1, &dir); |
/* turn left */ |
10 |
11 |
else if (front_open); |
|
/* drive |
straight*/ |
12 |
else if (right_open) turn(-1, &dir);/* turn right */ |
13 |
else turn(+2, &dir); |
/* go |
/* dead end - back up */ |
14 |
go_one(&x,&y,dir); |
one step |
in any case */ |
15}
16}
reached (x and y coordinates match). In each iteration, it is determined by reading the robot’s infrared sensors whether a wall exists on the front, left-, or right-hand side (boolean variables front_open, left_open, right_open). The robot then selects the “leftmost” direction for its further journey. That is, if possible it will always drive left, if not it will try driving straight, and only if the other two directions are blocked, will it try to drive right. If none of the three directions are free, the robot will turn on the spot and go back one square, since it has obviously arrived at a dead-end.
Program 15.2: Driving support functions
1 void turn(int change, int *dir)
2 { VWDriveTurn(vw, change*PI/2.0, ASPEED);
3VWDriveWait(vw);
4*dir = (*dir+change +4) % 4;
5}
1void go_one(int *x, int *y, int dir)
2{ switch (dir)
3{ case 0: (*y)++; break;
4case 1: (*x)--; break;
5case 2: (*y)--; break;
6case 3: (*x)++; break;
7}
8VWDriveStraight(vw, DIST, SPEED);
9VWDriveWait(vw);
10}
The support functions for turning multiples of 90° and driving one square are quite simple and shown in Program 15.2. Function turn turns the robot by the desired angle (r90° or 180°), and then updates the direction parameter dir.