-
class Nunchuk {
5
public:
-
void initialize();
-
bool update();
-
-
int joystick_x() const { return _buffer[0]; }
10
int joystick_y() const { return _buffer[1]; }
-
-
int x_acceleration() const {
-
return ((int)(_buffer[2]) << 2) | ((_buffer[5] >> 2) & 0x03);
-
}
15
-
int y_acceleration() const {
-
return ((int)(_buffer[3]) << 2) | ((_buffer[5] >> 4) & 0x03);
-
}
-
20
int z_acceleration() const {
-
return ((int)(_buffer[4]) << 2) | ((_buffer[5] >> 6) & 0x03);
-
}
-
bool z_button() const { return !(_buffer[5] & 0x01); }
-
bool c_button() const { return !(_buffer[5] & 0x02); }
25
-
private:
-
void request_data();
-
char decode_byte(const char);
-
30
unsigned char _buffer[NUNCHUK_BUFFER_SIZE];
-
};
-
-
#endif
-
This small C++ class is all you need to use a Nunchuk controller with your
Arduino. It starts with a double-include prevention mechanism: it checks
whether a preprocessor macro named
__NUNCHUK_H__
has been defined already
using
#ifndef
. If it hasn’t been defined, we define it and continue with the
declaration of the
Nunchuk
class. Otherwise, the preprocessor skips the decla-
ration, so you can safely include this header file more than once in your
application.
In line 3, we create a constant for the size of the array we need to store the
data the Nunchuk returns. We define this array in line 31, and in this case,
we define the constant using the preprocessor instead of the
const
keyword,
because array constants must be known at compile time in C++.
Then the actual declaration of the
Nunchuk
class begins. To initiate the commu-
nication channel between the Arduino and the Nunchuk, you have to invoke
report erratum • discuss
Building a Nunchuk Class • 149
www.it-ebooks.info