Hardware Reference
In-Depth Information
in the bedroom, turn off the TV, and other such instructions. These instruc-
tions are sent in small packets, and each packet ends with an exclamation mark.
There is a function available that reads in serial data and stops either when
all the data is read in, when there is a time-out, or when a special character is
received. This function is called readBytesUntil() and accepts one argument:
the character to wait for.
Serial.readBytesUntil(character, buffer, length);
Both readbytes() and readBytesUntil() return a byte of data: the amount
of characters read from the serial port. This will be zero if no data was received
because a time-out occurred, less than the expected length if some data was
received and a time-out occurred while waiting for the full packet, or the same
expected length if all the requested data were available. In the case of read-
BytesUntil() , non-zero values may also indicate that the terminator character
was detected.
Taking a Peek
There is a way to get hold of the i rst byte of data from the UART buffer without
modifying the buffer. There are several reasons why this might be useful to you.
When you know that data has arrived, what does it contain? Is this ASCII data
that needs to be put in a string? Or is this binary data that needs to be put in
another buffer? Would it help to know what the i rst character is? Well, you can.
Just like those who cheat when it is their birthday, there is a way to peek at data
without changing anything. This will return the i rst byte from the buffer, but
it will not remove the byte from the buffer. Again, it returns an int ; it returns
the i rst byte of data if it is available; otherwise it returns -1.
data = Serial.peek();
From here, you can read one or several bytes using the functions listed pre-
viously, and the i rst byte of data read with peek() will still be in the buffer.
Parsing Data
You have the data, but what do you do with it? Everything received is either
ASCII text or binary data. If it is binary data, then your program must analyze
the data and extract the data. ASCII, however, is received as text. This is great
if you want to know the user's name, but what if you ask him for his age? What
if the serial port receives an instruction to turn on an LED at a specii c light
setting? It might be text that represents an int or float , but how do you extract
that data? The answer is simple: You parse it.
 
Search WWH ::




Custom Search