After including all of the libraries we need, we define the
NUNCHUK_DEVICE_ID
constant. I
2
C is a master/slave protocol; in our case, the Arduino will be the
master, and the Nunchuk will be the slave. The Nunchuk registers itself at
the data bus using a certain ID (0x52), so we can address it when we need
something.
In
initialize
, we establish the connection between the Arduino and the Nunchuk
by sending a handshake. In line 7, we call
Wire
’s
begin
method, so the Arduino
joins the I
2
C bus as a master. (If you pass
begin
an ID, it joins the bus as a
slave having this ID.) Then we’ll begin a new transmission to the device
identified by
NUNCHUCK_DEVICE_ID
: our Nunchuk.
We send two bytes (0x40 and 0x00) to the Nunchuk, and then we end the
transmission. This is the whole handshake procedure, and now we can ask
the Nunchuk for its current status by calling
update
. In the following figure,
we see the message flow between an Arduino and a Nunchuk.
Arduino Nunchuk
6 data bytes
Handshake (0x40, 0x00)
Request new data (0x00)
6 data bytes
}
repeat
update
first pauses for a millisecond to let things settle. Then we request six
bytes from the Nunchuk, calling
Wire.requestFrom
. This doesn’t actually return
the bytes, but we have to read them in a loop and fill our buffer.
Wire.available
returns the number of bytes available on the data bus, and
Wire.read
returns
the current byte. We cannot use the bytes we get from the Nunchuk directly,
because the controller obfuscates them. “Decrypting” them is easy, as you
can see in
decode_byte
.
Finally, we call
request_data
to tell the Nunchuk to prepare new data. It transmits
a single zero byte to the Nunchuk, which means “prepare the next six bytes.”
Before we actually use our
Nunchuk
class in the next section, take a look at the
documentation of the Wire library. In the Arduino IDE’s menu, choose Help
> Reference and click the Libraries link.
report erratum • discuss
Building a Nunchuk Class • 151
www.it-ebooks.info