Datasheet
Chapter 3 • Assemble and Test your BOE Shield-Bot
96 • Robotics with the BOE Shield-Bot
How TestServoSpeed Works
The sketch TestServoSpeed increments the value of a variable named pulseWidth by 25
each time through a
for loop.
// Loop counts with pulseWidth from 1375 to 1625 in increments of 25.
for(int pulseWidth = 1375; pulseWidth <= 1625; pulseWidth += 25)
With each repetition of the for loop, it displays the value of the next pulse width that it will
send to the pin 13 servo, along with a user prompt.
Serial.print("pulseWidth = "); // Display pulseWidth value
Serial.println(pulseWidth);
Serial.println("Press a key and click"); // User prompt
Serial.println("Send to start servo...");
After Serial.begin in the setup loop, the Arduino sets aside some memory for characters
coming in from the Serial Monitor. This memory is typically called a serial buffer, and that’s
where ASCII values from the Serial Monitor are stored. Each time you use
Serial.read to
get a character from the buffer, the Arduino subtracts 1 from the number of characters
waiting in the buffer.
A call to
Serial.available will tell you how many characters are in the buffer. This sketch
uses
while(Serial.available() = = 0) to wait until the Serial Monitor sends a
character. Before moving on to run the servos, it uses
Serial.read( ) to remove the
character from the buffer. The sketch could have used
int myVar = Serial.read( ) to
copy the character to a variable. Since the code isn’t using the character’s value to make
decisions, it just calls
Serial.read, but doesn’t copy the result anywhere. The important
part is that it needs to clear the buffer so that
Serial.available( ) returns zero next time
through the loop.
while(Serial.available() == 0); // Wait for character
Serial.read(); // Clear character
Where is the while loop’s code block? The C language allows the while loop to use an empty
code block, in this case to wait there until it receives a character. When you type a character into
the Serial Monitor, Serial.available returns 1 instead of 0, so the while loop lets the sketch
move on to the next statement. Serial.read removes that character you typed from the
Arduino’s serial buffer to make sure that Serial.available returns 0 next time through the
loop. You could have typed this empty while loop other ways:
while(Serial.available() == 0) {}
...or:
while(Serial.available() == 0) {};