Go Down

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


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.


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.
The art of getting good answers lies in asking good questions.


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 will NOT respond to personal messages, I WILL delete them, use the forum please ]

Coding Badly

Peek is a fundamental piece of...

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


Thanks guys, all clear now.

Go Up