#include <Wire.h>
void setup()
{
Serial.begin(19200);
nunchuck_init();
Serial.print ("Finished setup\n");
}
void loop()
{
nunchuck_get_data();
nunchuck_print_data();
delay(100);
}
static uint8_t nunchuck_buf[6];
void nunchuck_init()
{
Wire.begin();
Wire.beginTransmission(0x52);
Wire.write(0x40);
Wire.write(0x00);
Wire.endTransmission();
}
void nunchuck_send_request()
{
Wire.beginTransmission(0x52);
Wire.write(0x00);
Wire.endTransmission();
}
int nunchuck_get_data()
{
int cnt=0;
Wire.requestFrom (0x52, 6);
while (Wire.available ()) {
nunchuck_buf[cnt] = nunchuk_decode_byte(Wire.read());
cnt++;
}
nunchuck_send_request();
if (cnt >= 5) {
return 1;
}
return 0;
}
void nunchuck_print_data()
{
static int i=0;
int joy_x_axis = nunchuck_buf[0];
int joy_y_axis = nunchuck_buf[1];
int accel_x_axis = nunchuck_buf[2];
int accel_y_axis = nunchuck_buf[3];
int accel_z_axis = nunchuck_buf[4];
int z_button = 0;
int c_button = 0;
if ((nunchuck_buf[5] >> 0) & 1)
z_button = 1;
if ((nunchuck_buf[5] >> 1) & 1)
c_button = 1;
if ((nunchuck_buf[5] >> 2) & 1)
accel_x_axis += 2;
if ((nunchuck_buf[5] >> 3) & 1)
accel_x_axis += 1;
if ((nunchuck_buf[5] >> 4) & 1)
accel_y_axis += 2;
if ((nunchuck_buf[5] >> 5) & 1)
accel_y_axis += 1;
if ((nunchuck_buf[5] >> 6) & 1)
accel_z_axis += 2;
if ((nunchuck_buf[5] >> 7) & 1)
accel_z_axis += 1;
Serial.print(i,DEC);
Serial.print("\t");
Serial.print("joy:");
Serial.print(joy_x_axis,DEC);
Serial.print(",");
Serial.print(joy_y_axis, DEC);
Serial.print(" \t");
Serial.print("acc:");
Serial.print(accel_x_axis, DEC);
Serial.print(",");
Serial.print(accel_y_axis, DEC);
Serial.print(",");
Serial.print(accel_z_axis, DEC);
Serial.print("\t");
Serial.print("but:");
Serial.print(z_button, DEC);
Serial.print(",");
Serial.print(c_button, DEC);
Serial.print("\r\n");
i++;
}
char nunchuk_decode_byte (char x)
{
x = (x ^ 0x17) + 0x17;
return x;
}