Hardware Reference
In-Depth Information
of bytes does not mean that the slave will send that amount of data; it could be
less. To see if any data is available in the buffer, call
Wire.available()
.
number = Wire.available();
Wire.available()
looks at the buffer and returns the amount of bytes remain-
ing. It can be used with
Wire.read()
to create a routine that does not block if
data is not available.
while(Wire.available()) // Repeat as long as there is data waiting
{
char c = Wire.read(); // Read in one byte
Serial.print(c); // Print the byte
}
Slave Communications
Most people expect the Arduino to be an I
2
C master, controlling the network.
In some cases, it can be useful to have an Arduino as an I
2
C slave, especially
when several Arduinos are to be used. Arduinos also have a major advantage
over other I
2
C devices; you can specify any address you see i t. You can have
a total of 128 Arduino slaves on an I
2
C network, which should be more than
enough to fully automate your house.
You do not know when an I
2
C master will send or request information, and
a sketch cannot be told to hold indei nitely while waiting for information. To
allow a sketch to continue while waiting for an I
2
C request, the Wire library
allows you to create
callbacks
, functions that are called when an event occurs.
The I
2
C callbacks are
Wire.onReceive()
(when the Arduino receives informa-
tion) and
Wire.onRequest()
(when the Arduino is requested for information).
Receiving Information
Wire.onReceive()
is called when a master sends information to a slave. To
create this callback, you must create a function. The name can be anything you
choose, but it must accept one parameter, an
int
(the number of bytes received
from the master).
void receiveData(int byteCount)
{
// Put your code here
}
Wire.onReceive(receiveData); // Create the callback
Search WWH ::
Custom Search