Hardware Reference
In-Depth Information
Listing 8-2: ( continued)
48 Serial.println("LED is ON");
49 break;
50 default:
51 Serial.println("Unknown status detected");
52 break;
53 }
54 }
This sketch starts the same as the slave sketch; the Wire library is imported,
and the address of the slave is dei ned. setup() is almost identical, except on
line 11, begin() does not take an address parameter because this is the master.
Unlike the slave sketch, the master sketch uses loop() . It is designed to tell
the slave to turn on its LED, wait for a few milliseconds, and then tell the slave
to turn off its LED. After each transmission, it requests a byte of information to
know the current state of the LED.
On line 16, the sketch begins creating a message. Wire.beginTransmission()
requires one parameter, the destination address, which in this case is the slave
Arduino. A message is created in a buffer but not sent. The Arduino auto-
matically formats the message as required. On line 17, a byte is added to the
message—a simple value: 1. According to the project specii cations, sending a
1 to the slave turns on the LED. The instruction is added, but the message is
not complete. Another step is required: Wire.endTransmission() . On line 18,
that is exactly what is done. By using default settings, the message is sent and
the I 2 C bus is freed.
To illustrate what is going on, the master also turns its LED on and off. This
is what is done on line 19. On line 22, printLight() is called. This function is
declared on line 37. It requests a byte from the slave, and prints the result in
readable format.
To request data from a slave, Wire.requestFrom() is called. This is done on
line 39. The i rst parameter is the address; in this case, the slave. The second
parameter is the number of bytes to return—in this case: a single byte. When
the order is sent, the sketch waits for a read() operation to complete, on line
41. That data is then fed into a switch statement, and the data is printed to the
serial line.
When the sketch i nishes turning the slave's LED on, the entire process is
repeated with an order to turn the LED off.
Exercises
This sketch can control one LED by sending 1 byte, telling the slave to either
turn the LED on or off. By sending 2 bytes, you could tell the slave to turn on one
of several LEDs. Try to modify this sketch to turn on several LEDs. Remember
 
Search WWH ::




Custom Search