Pololu Robotics & Electronics
My account Comments or questions? About Pololu Contact Ordering information Distributors

Pololu Forum

Serial.flush in the Arduino Cookbook

I have two quesitons.

  1. I read that Serial.flush no longer empties the incoming buffer. I bought the "Arduino Cookbook by Michael Margolis and I am trying to understand the example code and do the experiment. Serial.flush is part of his program. Is there a replacement for this? However I still tried the experiment and it works with Serial.flush.

  2. In the same experiment, the function: boolean configureRadio() either returns a “true” or “false” ? Is this like an if statement, in that if the function returns a true, then the rest of the program runs. If the function returns a false, then the function starts over again until it returns a true?

Thank you very much :slight_smile:

Here is the code:

  Read an analog value from an XBee API frame and set the brightness
  of an LED accordingly.

const int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
  configureRadio(); // check the return value if you need error handling

boolean configureRadio() {

  // put the radio in command mode:

  String ok_response = "OK\r"; // the response we expect.

  // Read the text of the response into the response variable
  String response = String("");
  while (response.length() < ok_response.length()) {
    if (Serial.available() > 0) {
      response += (char) Serial.read();

  // If we got the right response, configure the radio and return true.
  if (response.equals(ok_response)) {
    Serial.print("ATAP1\r"); // Enter API mode
    Serial.print("ATCN\r");  // back to data mode
    return true;
  } else {
    return false; // This indicates the response was incorrect.

void loop() {

  if (Serial.available() >= 14) { // Wait until we have a mouthful of data

     if (Serial.read() == 0x7E) { // Start delimiter of a frame

      // Skip over the bytes in the API frame we don't care about
      for (int i = 0; i < 10; i++) {

      // The next two bytes are the high and low bytes of the sensor reading
      int analogHigh = Serial.read();
      int analogLow = Serial.read();
      int analogValue = analogLow + (analogHigh * 256);

      // Scale the brightness to the Arduino PWM range
      int brightness = map(analogValue, 0, 1023, 0, 255);

      // Light the LED
      analogWrite(ledPin, brightness);
  1. You are right, I looked at the source code of Serial.flush() and all it does is wait for the bytes in the transmit buffer to finish being sent. If you want to get rid of all the buffered incoming data you can do:
while (Serial.read() != -1);
  1. No, a return value does not imply an if statement. In the example code you posted, the return value of configureRadio is ignored by the function that calls it.