the
initialize
method once. Then you call
update
whenever you want the Nunchuk
to send new data. You’ll see the implementation of these two methods shortly.
We have public methods for getting all of the attributes the Nunchuk returns:
the x and y positions of the analog stick, the button states, and the accelera-
tion values of the x-, y-, and z-axes. All of these methods operate on the raw
data you can find in the buffer in line 31. Their implementation is mostly
trivial, and it requires only a single line of code. Only the assembly of the 10-
bit acceleration values needs some tricky bit operations (see Bit Operations,
on page 251).
At the end of the class declaration, you’ll find two private helper methods
named
request_data
and
decode_byte
. We need them to implement the
initialize
and
update
methods:
Tinkering/NunchukDemo/nunchuk.cpp
#include <Arduino.h>
Line 1
#include <Wire.h>
-
#include "nunchuk.h"
-
#define NUNCHUK_DEVICE_ID 0x52
-
5
void Nunchuk::initialize() {
-
Wire.begin();
-
Wire.beginTransmission(NUNCHUK_DEVICE_ID);
-
Wire.write((byte)0x40);
-
Wire.write((byte)0x00);
10
Wire.endTransmission();
-
update();
-
}
-
-
bool Nunchuk::update() {
15
delay(1);
-
Wire.requestFrom(NUNCHUK_DEVICE_ID, NUNCHUK_BUFFER_SIZE);
-
int byte_counter = 0;
-
while (Wire.available() && byte_counter < NUNCHUK_BUFFER_SIZE)
-
_buffer[byte_counter++] = decode_byte(Wire.read());
20
request_data();
-
return byte_counter == NUNCHUK_BUFFER_SIZE;
-
}
-
-
void Nunchuk::request_data() {
25
Wire.beginTransmission(NUNCHUK_DEVICE_ID);
-
Wire.write((byte)0x00);
-
Wire.endTransmission();
-
}
-
30
char Nunchuk::decode_byte(const char b) {
-
return (b ^ 0x17) + 0x17;
-
}
-
Chapter 9. Tinkering with the Wii Nunchuk • 150
report erratum • discuss
www.it-ebooks.info