Go Down

Topic: What is serial.peek for? (Read 509 times) previous topic - next topic

Lakes

Quote
Returns the next byte (character) of incoming serial data without removing it from the internal serial buffer. That is, successive calls to peek() will return the same character, as will the next call to read()


I don`t understand the point this function, if successive calls to peek() result in the same character, what use is it?

If successive peek calls returned each character stored in the buffer, that I could understand.

PaulS

It lets you look at the next character, and decide whether or not you want to read it. If you are reading a stream of characters that are numeric digits, and the next character is not a numeric digit, you might want to wait to actually read that character until after dealing with what you have already read.

MarkT

The point is when you are trying to make sense of an input string (this is called parsing).  One function might try to recognise and read a decimal number, say, and another might look for a separator such as ','.

The ability to look at the next char without reading it means each function can see if the input is relevant for it, and if not it hasn't prevented the next function from seeing that input.
[ I won't respond to messages, use the forum please ]

Coding Badly


Peek is a fundamental piece of...
http://en.wikipedia.org/wiki/LALR_parser

Parsing a stream of characters for a number is an excellent example.

Lakes

Thanks guys, all clear now.

Go Up