How DisplayWhiskerStates Works

In the setup function, pinMode(7, INPUT) and pinMode(5, INPUT) set digital pins 7 and 5 to input so they can monitor the voltages applied by the whisker circuits.

  pinMode(7, INPUT);          // Set right whisker pin to input
  pinMode(5, INPUT);          // Set left whisker pin to input

In the loop function, each call to digitalRead returns a 0 if the whisker is pressed or 1 if it is not.  Those values get copied to variables named wLeft and wRight, which are short for whisker-left and whisker-right.

  byte wLeft = digitalRead(5);     // Copy left result to wLeft  
  byte wRight = digitalRead(7);    // Copy right result to wRight

Next, Serial.print displays the value of wLeft to the Serial Monitor, and Serial.println displays the value of wRight and a carriage return.

  Serial.print(wLeft);             // Display left whisker state
  Serial.println(wRight);          // Display right whisker state

Before the next repetition of the loop function, there’s a delay(50).  This slows down the number of messages the Serial Monitor receives each second.  Although it’s probably not needed, we leave it in to prevent possible computer buffer overruns (too much data to store) for older hardware and certain operating systems.

Your Turn – Nesting Function Calls

Your sketch doesn’t actually need to use variables to store the values from digitalRead.  Instead, the (1 or 0) value that digitalRead returns can be used directly by nesting the function call inside Serial.print and sending its return value straight to the Serial Monitor.  In that case, your loop function would look like this:

void loop()                        // Main loop auto-repeats
{                                            
  Serial.print(digitalRead(5));    // Display wLeft
  Serial.println(digitalRead(7));  // Display wRight

  delay(50);                       // Pause for 50 ms
}            
  • Replace the loop function with the one above, upload the sketch, and test the whiskers to verify that it functions the same.