-1

I am communicating with the esp8266 WiFi module using Arduino. The module returns GET requests from other clients. They will be of the form

GET /101011 HTTP/1.1\r\nHost...

I wish to extract only the 101011 from the received serial data and discard the rest. I came up with this small chunk of code to test it by sending data from my laptop.

This is the code:

String s;
void setup() {
 Serial.begin(9600);
}
void loop() {
 if(Serial.available())
 {
 Serial.println("Inside");
 Serial.find("/");
 s = Serial.readStringUntil(' ');
 Serial.println(s);
 // Discard the rest of the data . Snippet from Jeremy Blum's Blog
 while(Serial.available()>0) Serial.read(); 
 }
}

Jeremy's Blog

But when I run this using the input GET /101011 HTTP/1.1\r\n the output produced is

Inside
101011
Inside
1.1\r\n

Why is Serial.available() returning true even after reading everything? How to discard the rest of data from the serial input buffer?

asked Mar 27, 2016 at 11:30
3
  • 3
    How do you know you have read everything? Serial data is still arriving from the ESP8266 while you are clearing the buffer - and you are clearing it much faster than the data is arriving. Remember: serial data arrives s...l...o...w...l...y... Commented Mar 27, 2016 at 11:52
  • Read this:~ hackingmajenkoblog.wordpress.com/2016/02/01/… Commented Mar 27, 2016 at 11:52
  • @Majenko Thank you. Read your blog. Will try to implement it in my design. Commented Mar 27, 2016 at 12:02

1 Answer 1

2

One possible approach is to read and discard everything for a fixed time, like a second. For example:

unsigned long now = millis ();
while (millis () - now < 1000)
 Serial.read (); // read and discard any input

I'm not a big fan of trying to "flush the input buffer". How do you know if a second is long enough? Or maybe it is too long? You are better off reading to some known delimiter.

answered Mar 28, 2016 at 4:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.