Hardware Reference
In-Depth Information
You can also evaluate if there are a certain number of bytes with an if()
statement:
if (Serial.available() > 0)
{
// Read in serial data
}
Trying to read the serial buffer if no data is available can waste time in your
sketch. To avoid a sketch freezing while waiting for data, you can change the
duration of the serial time-out, as explained here.
Reading a Byte
You can read a byte from the data buffer using the read() function. This function
takes 1 byte from the UART buffer and returns it to the program. This function
does not return a byte , instead, it returns an int . There is a good reason for
this. What would happen if the buffer were empty? Would the function return
0? That might be the byte waiting for the user in the buffer; there is no way of
telling. Instead, the read() function returns an int . The return values are in the
range of 0 to 255, or -1 if no data is available. This function returns immediately
and does not wait for data to arrive.
Reading Multiple Bytes
Reading in a single byte at a time can be tedious; fortunately there are other
ways of getting data from a serial connection.
readBytes() reads multiple bytes from a serial port and places them into
a buffer.
Serial.readBytes(buffer, length);
You must specify the amount of bytes to read, in which case the function
stops when all the data has been received. There is also another reason why this
function might stop; asking this function for more characters than is available
could cause the Arduino to momentarily stall while waiting for data that may
never arrive. To avoid this, there is a time-out for waiting to read serial data. The
time-out is set by setTime-out(). It takes one parameter: a long that contains
the number of milliseconds to wait for all the data to arrive. By default, serial
ports time out after 1 second.
Serial.setTime-out(time);
You can now retrieve multiple bytes and time out if no data is available.
However, the Arduino still has one trick left. Imagine working with a protocol
that allows your computer to send messages to an Arduino: turn on the lights
 
Search WWH ::




Custom Search