Datasheet

Chapter 5 Tactile Navigation with Whiskers
170Robotics with the BOE Shield-Bot
5. If one condition turns out to be true, the code might need to evaluate another
condition with a nested
if statement.
Exercise Solutions
1. Since digitalRead returns 1 or 0, your code can multiply digitalRead(5) by
2 and store the result in the
whiskers variable. It can then add the result of
digitalRead(7) to the whiskers variable and the result will be 3 for no
whiskers.
// Robotics with the BOE Shield Chapter 5, Exercise 1
// Value from 0 to 3 indicates whisker states:
// 0 = both, 1 = left, 2 = right, 3 = neither.
void setup() // Built-in initialization block
{
tone(4, 3000, 1000); // Play tone for 1 second
delay(1000); // Delay to finish tone
pinMode(7, INPUT); // Set right whisker pin to input
pinMode(5, INPUT); // Set left whisker pin to input
Serial.begin(9600); // Set data rate to 9600 bps
}
void loop() // Main loop auto-repeats
{
byte whiskers = 2 * digitalRead(5);
whiskers += digitalRead(7);
Serial.println(whiskers); // Display wLeft
delay(50); // Pause for 50 ms
}
2. In the if((wLeft == 0) && (wRight == 0)) block, remove
the
backward and turnLeft function and replace them with calls
to
servoLeft.detach and servoRight.detach.
void loop() // Main loop auto-repeats
{
byte wLeft = digitalRead(5); // Copy right result to wLeft
byte wRight = digitalRead(7); // Copy left result to wRight
if((wLeft == 0) && (wRight == 0)) // If both whiskers contact
{
pause(500); // Pause motion for 0.5 seconds