Serial Doesn't Wait on Input

Sure it works in specific cases, just like emptying the serial input buffer would work if you have had any delay in the code before or were using a faster baud rate.. it works until it does not

It’s not just telnet, I often use coolTerm as an alternative Serial monitor than the one bundled with the IDE (which is buggy and slow with IDE 2.0 beta) and it would send keys as you type them in.

Again I’m not saying your code does not work, I am saying your are twisting the reality for Robyn’s tutorial and then claiming it’s not correct. This is disappointing.

Serial Basics was offered up as a solution for the OP, but is no different to the OPs existing code.

while(Serial.available() != 0) {
Serial.readBytes(wrk,1);
} 

In this case (and lots of others) Serial Basic's 'flush' is not useful, because in your own words

My suggested code handles this case to my satisfaction. Serial Basics does not.

You are twisting facts again.

The suggestion was to study the tutorial to understand what was going on. I hinted also at what too look for

You have attempted to second guess timing on a asynchronous protocol and likely got it wrong… the data might still have been incoming

The aim is helping members become more savvy with what’s going on, not hand them over fully baked answers that come with tons of different custom imbricated libraries to accept as a whole and leave them as clueless as they were before with a mountain of fundamental concepts unacquierd. That’s should be the purpose of a tutorial, and Robin’s hits it as the name implies, it is really about understanding the basics. . A must have for anyone dealing with Serial communication

Thanks all for the good comments.
As in most cases in the computer programming field for me, it comes down to good documentation and this is generally lacking.
dumpf--thank you for your well thought out documentation. Certainly more detailed than what was provided by the vendor
I never did use the vendor flush() command in my code. The vendor clearly described it and it was not what I needed. When I used the phrase "flush" I was referring to a routine that I wrote and I believe it does the same thing that robin2 did.
The problem with a lot of serial excahnge is that the reader generally does not have control over what the writer is doing, the latter often belonging to a third party.
A few years back I had to read 9 datastreams from a COB TI processor at 115kbaud. This happening 6000m in the ocean where failure is not an option. In that case I had control of both ends and I used error checking bytes to end each volley. And as you can imagine, even using FPGAs for the transmitter, byte loss was frequent so it was important. Noisy too--Lots of caps and coils to hedge my bet on that project.
In view of the above there is NEVER an "end of data" condition if you don't have control of the sender--so has to "improvise". Fortunately, most senders have some reasonable ending-often after 1 second for example. But it is always a risk.
In the present case I finally put the "sender" on the scope and I see additional bytes quite late in the game (200ms). A bit unusual for most of the devices that I use but it happens. Looks like noise on there too-the device runs steppers and I don't see filters, coils etc that one might want to apply on this board. I will probably use my own boards for this in a few months.
On other platforms I tend to use/need interrupt based IO and in those cases I let the bytes flow and examine them when I need them to see if they fit the "protocol" which is user determined.

Looking back as my next b'day approaches in a few days, I think my first serial code was 49 years ago on UNIVAC processors. The baud rate was 120. And there were no "ser" routines to worry about --I had to bit bang the serial protocol from scratch on a "line controller" the size of a refrigerator. Jeesh--that added a new dimension to slow (actually OLD dimension?)-and the receiver was a teletype complete with a paper tape punch.
I rarely use Arduinos (and computers is not my main field)- I grabbed an Arduino off my electronics bench because I ran out of unpopulated boards that I build using PICs-it got me thru my work yesterday. --Once I work out the bugs (this is an optical device) I will board the whole thing out on tiny PICs or STMs.
Atmels are fine-very similar to the PIC and I admire what Arduinos have done-they just postdate me a lot and I have not needed them (unless I am in the above pinch).
The vendor did not document the details of the serial protocol - I assume they expect one to know the underpinnings of serial. If I had time to program the Atmel directly with STUDIO etc I would start from basics. However, being somewhat user friendly I expected that some timing constraints etc were assumed by the Arduino vendor and some flushing, waiting etc would be done by their routines.
Probably they could have a little more deliberation in their doc. It is not clear if the "tutorial" was written by the vendor-and I usually look for a lot more detail when I do use them-the vendor datasheets are more helpful in those cases. Atmel did a pretty good job on thiers.

Nonetheless they have done an admirable job of making computing comparatively straightforward.

Thanks all
Fritz

In answer to the OP's original question, a very simple and effective replacement code to "Wait on Input and clear it" is just

Serial.readString();

This waits for upto 1sec for chars to arrive and then consumes all incoming chars until none arrive for 1sec.
You can change the 1sec timeout using Serial.setTimeout( ) i.e.

Serial.setTimeout(350);  // change to 350mS leading and trailing
Serial.readString();
Serial.setTimeout(1000);  // back to default setting

If you only want to clear input that has already started to arrive you can use

if (Serial.available()) {
   Serial.readString();
}

On small memory Arduino AVR boards like Uno and Mega, this code is completely safe and will consume and discard an infinite number of arriving chars without crashing the sketch.

As the chars are read into the String it allocates more heap memory, but when the available memory is down to 128bytes, the String re-allocate fails and all further chars are just discarded.

Then when the readString() method returns, the method local String in readString() goes out of scope and is discarded along with all the heap it was using. The readString() method returns a copy of the String read but if the compiler does not optimize that away, it is just immediately discarded as there is no assignment. Again any attempt to allocate memory for the return String just safely fails if there would be less than 128 bytes of memory (heap/stack) remaining.

The memory available before calling the Serial.readString(); statement equals the memory available after this statement returns, with no memory fragmentation, even if 100K's of chars are read.

What about learning and understanding how to do this yourself without allocating any big chunk of memory at all so that you have a solution that works across all architectures?…

Serial Input Basics and Using millis() for timing. A beginners guide and Several things at the same time should be the first stop for whoever wants to use her/his brain and understand / be on top of what’s going on.

If you plan to discard the data, not collecting it in the first place seems the most reasonable approach (as your flush function would do)

Some times you just want a quick fix that works, using a one-liner and a language supplied function, so you can get on with the meat of the project :slight_smile:
You cannot learn everything at once.

The non-blocking input flushing code examples in my Arduino Software Solutions tutorial handles that case. But once you get past Uno and Mega, you need to be flushing kilobytes of input before you would expect to see any problems with just using readString(); on other boards.

My biggest reservation about using readString() is that if you use it in the loop() you will get a 1sec delay
But "Horses for courses". Lots of beginner's code starts out using delays (see the Arduino IDE blink example) which they may or may not replace later if the delays become a problem for their project.

Helping people learn the fundamentals should be the first goal here.

Quick hacks are OK if OP has no interest in learning and you want to support this type of request and use your time that way.

I prefer to contribute towards people who want to learn and become self sufficient, possibly helping the next generation of engineers get started or youngsters getting "hooked" into the fun of science, engineering work and intellectual discipline/ambition (and give them a reason to do something else than loosing their days on so called "social networks").

Between us we will cover 'all basis'

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