Electric Imp with Wii Nunchuck I2C

I managed to get the Electric Imp to talk to a Wii Nunchuck using I2C. This is a pretty nice way to get an analogue XY Joystick, 3 axis accelerometer, and 2 digital buttons quickly into an imp project.

The circuits and Device Code are bellow - I just used a RGB LED to demo that the inputs were working OK.

Proto-Circuit - uses a Nunchuck connector

Nunchuck Circuit

LED Circuit

— YouTube demo —

Device Code
`//Wii nunchuck i2c program
//Connections
//April electric imp — Wii nunchuck
// Pin 1 (SCL), clock — i2c,c
// Pin 2 (SDA), data — i2c,d
// Pin 3V3 — pwr,+
// Pin GND — pwr,-
// Pin 7 — LED, Red — 330 Ohm — Gnd
// Pin 8 — LED, Green — 330 Ohm — Gnd
// Pin 9 — LED, Blue — 330 Ohm — Gnd

function read_nunchuck() {
hardware.i2c12.write(0xA4,format("%c",0x00));
local result = hardware.i2c12.read(0xA5,"", 6);

//Decode Joystick
local joyx=((result[0] ^ 0x17) + 0x17)/255.0;
local joyy=((result[1] ^ 0x17) + 0x17)/255.0;

// Decode Accelerometer
local accx = ((result[2] ^ 0x17) + 0x17)/255.0;
local accy = ((result[3] ^ 0x17) + 0x17)/255.0;
local accz = ((result[4] ^ 0x17) + 0x17)/255.0;

// Decode Buttons
local buttons=(result[5] & 0x03);
/*
buttons = 0 if ‘Z’ only pressed
buttons = 1 if ‘C’ only pressed
buttons = 2 if ‘Z’ and ‘C’ pressed
buttons = 3 if none pressed
*/
local zbutt=0
local cbutt=0
if (buttons == 0){
zbutt=1;
}
else if (buttons == 1){
cbutt=1;
}
else if(buttons == 2){
zbutt=1;
cbutt=1;
}

//4 options for lighting RGB LED based on button presses and joystick position
if (cbutt==0){ //c button is unpressed
if (zbutt==0){
//if nothing is pressed, kill all the LEDs
led(0,0,0);
}
else {
//Only Z button pressed, control Blue Brigtness with JoyX
led(0,0,joyx);
}
}
else { //c button is pressed
if (zbutt==0){
//Only C button pressed, control Green Brigtness with JoyX
led(0,joyx,0);
}
else
{
//Both buttons pressed, control R/G with Joystick
led(joyx,joyy,0);
}
}
imp.wakeup(0.001,read_nunchuck); //rerun the main loop every 1 msec
}

function led(r,g,b){
//Light LED RGB on pins 7, 8, 9 based on button presses and Joystick
hardware.pin7.write®;
hardware.pin8.write(g);
hardware.pin9.write(b);
}

function config_i2c(){
// configure the i2c()
hardware.i2c12.configure(CLOCK_SPEED_100_KHZ);
// handshake to initiate Nunchuck
hardware.i2c12.write(0xA4,format("%c%c",0x40,0x00));
}

function config_led(){
// Configure PWMs to power LED
hardware.pin7.configure(PWM_OUT, 0.001, 0); //red
hardware.pin8.configure(PWM_OUT, 0.001, 0); //green
hardware.pin9.configure(PWM_OUT, 0.001, 0); //blue
}

//Configure then start the main loop
config_i2c();
config_led();
read_nunchuck();

/*web links
http://web.engr.oregonstate.edu/~sullivae/ece375/pdf/nunchuk.pdf


http://www.robotshop.com/media/files/PDF/inex-zx-nunchuck-datasheet.pdf

Note: some sites call for 52 as the address, but the imp works with A4
this is because the 52 is a 7 bit, but some devices prefer 8 bit
so you need to move it over 1 bit, or multiply by 2
*/`