Pages: [1]   Go Down
Author Topic: What is serial.peek for?  (Read 477 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Sr. Member
****
Karma: 6
Posts: 429
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 617
Posts: 49463
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

0
Offline Offline
Shannon Member
****
Karma: 207
Posts: 12205
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

[ I won't respond to messages, use the forum please ]

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 208
Posts: 12943
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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.
Logged

Offline Offline
Sr. Member
****
Karma: 6
Posts: 429
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks guys, all clear now.
Logged

Pages: [1]   Go Up
Jump to: