Datasheet
Chapter 5 • Tactile Navigation with Whiskers
166 • Robotics with the BOE Shield-Bot
if((wLeft != wLeftOld) && (wRight != wRightOld))
{
counter++; // Increase count by one
wLeftOld = wLeft; // Record current for next rep
wRightOld = wRight;
If this is the fourth consecutive alternate whisker contact, then it’s time to reset
the
counter variable to 0 and execute a U-turn. When the if(counter == 4) statement is
true, its code block tricks the whisker navigation routine into thinking both whiskers are
pressed. How does it do that? It sets both
wLeft and wRight to zero. This makes the
whisker navigation routine think both whiskers are pressed, so it makes a U-turn.
if(counter == 4) // Stuck in a corner?
{
wLeft = 0; // Set up whisker states for U-turn
wRight = 0;
counter = 0; // Clear alternate corner count
}
}
But, if the conditions in if((wLeft != wLeftOld) && (wRight != wRightOld)) are
not all true, it means that this is not a sequence of alternating whisker contacts anymore, so
the BOE Shield-Bot must not be stuck in a corner. In that case, the
counter variable is set to
zero so that it can start counting again when it really does find a corner.
else // Not alternate from last time
{
counter = 0; // Clear alternate corner count
}
}
One thing that can be tricky about nested if statements is keeping track of opening and
closing braces for each statement’s code block. The picture below shows some nested
if
statements from the last sketch. In the Arduino and codebender : edu editors, you can
double-click on a brace to highlight its code block. But sometimes, printing out the code and
simply drawing lines to connect opening and closing braces helps to see all the blocks at
once, which is useful for finding bugs in deeply nested code.
In this picture, the
if(wLeft != wRight) statement’s code block contains all the rest of the
decision-making code. If it turns out that
wLeft is equal to wRight, the Arduino skips to
whatever code follows that last closing brace
}. The second level if statement compares
the old and new
wLeft and wRight values with if ((wLeft != wLeftOld) && (wRight
!= wRightOld))
. Notice that its code block ending brace is just below the one for the
if(counter==4) block. The if ((wLeft != wLeftOld) && (wRight != wRightOld))