Problem with flushing buffer?

// **heres my code to the simple answering machine. the concept is i want the code to first tell me that the bot is ready to chat. After that id simply send any character as an input on the serial monitor so that it can give the response " yes " irrespective of what the input message was. The problem im facing right now is when i send an input character the output ends up being a repeating "yes" instead of a single one. Am i making any mistakes here or is my board not flushing the serial buffer properly?
**//

bool mail;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);                      // set baud rate
  Serial.println(" Robobot is ready to chat"); // allow for the user to acknowledge the system is on
}

void loop() {
 mail = Serial.available() // check if a message came 
  if( mail == LOW);  // if mail is low do nothing, if there was a message present (Serial.available) then print "yes "
  else {           
    delay(1000);           // add some delay so the message "yes" doesnt arrive immediately
    Serial.println("Yes");
    mail = LOW             // set mail back to LOW
    word flush();          // clear the serial buffer 
  }
 }

Can you talk us through that, please?

i tried to clear the serial buffer, after the program would print " yes"

Welcome to the forum

You could start by using the correct data type for the mail variable if you are going to use it to hold the value returned by Serial.available()

To compound the problem you later test the value of the mail variable to see whether it is LOW.

Why not simply test whether Serial.available() returns true indicating that data is available to read then take action. One of those actions should be to actually read the available data to empty the buffer otherwise Serial.available() will continue to return a number greater than 0

flush() makes sure that any characters you are trying to send have left the buffer. It has nothing to do with clearing out the input buffer. You have to read() a byte at a time until it is empty.

thank you, i see how this command works now :smiley:

thank you this helped out alot :pray:

But we can't see where you defined the function "flush", not did you explain what the word "word" is doing there.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.