Hardware Reference
In-Depth Information
can also be used for inter-device communication, like in this project, but in that
case, the grounds must be connected.
The slave Arduino will turn on and off the on-board LED according to mes-
sages from the master. The master can send “0” to turn the LED off and “1” to
turn the LED on. It can also request a byte of data from the slave; this data will
be the current state of the LED. The master will also turn its LED on and off, so
you should see a perfectly synchronized pair of LEDs.
Time to start, so start with the slave. The code is simple as shown in Listing 8-1.
Listing 8-1: The Slave (fi lename: Chapter8bSlave.ino).
1 #include <Wire.h>
2
3 #define SLAVE_ADDRESS 0x08
4 int data = 0;
5 int state = 0;
6
7 void setup()
8 {
9 pinMode(13, OUTPUT); // Internal LED
10 Serial.begin(9600);
11 Wire.begin(SLAVE_ADDRESS); // Initialize as I2C slave
12
13 // Register I2C callbacks
14 Wire.onReceive(receiveData);
15 Wire.onRequest(sendData);
16 }
17
18 void loop()
19 {
20 // Nothing to do
21 delay(100);
22 }
23
24 // Callback for data reception
25 void receiveData(int byteCount)
26 {
27 while(Wire.available())
28 {
29 data = Wire.read();
30 Serial.print("Data received: ");
31 Serial.println(data);
32
33 if (data == 1)
34 {
35 digitalWrite(13, HIGH); // Turn the LED on
36 state = 1;
37 }
38 else
continues
Search WWH ::




Custom Search