Tuesday, July 20, 2010

Wii Nunchuck for arduino with Python serial reader

Today I followed the excellent tutorial on Windmeadow about how to read data from a wii nunchuck using an arduino. It's my first real dive into electronics. But I'll do my best to explain.

My setup used an arduino duemilanove. The advantage compared to the board used in the Windmeadow post is that the duemilanove actually has a 3.3V supply (which is what the nunchuck wants apparently). I already had some male-male jumper wires so I didn't need to strip apart my nunchuck, I was able to push the wires into the right places. If you can imagine the back of the nunchuck connector looking like this:
Clock Empty Ground
Empty
3.3V Empty Data

Then the connections need to be made to the arduino as below.

Wii Arduino
Top Left (Clock) Analog In 4
Top Right (Ground) Ground4
Bottom Left (3.3v) 3.3V
Bottom Right (Data) Analog In 5

From this point you should be able to follow the code in the Windmeadow post to get some working firmware, The only alteration I made was to print to serial in a way that was going to be easy to parse:
void print_for_python(int x, int y) {
    Serial.print(0x00, BYTE);    
    Serial.print(x, BYTE);
    Serial.print(0x01, BYTE);
    Serial.print(y, BYTE);
}

I could then write a simple python script using pySerial
import serial
import struct
ser = serial.Serial('/dev/ttyUSB1')
ser.baudrate = 19200
print ser.portstr
while True:
    line = ser.read(1)
    b = struct.unpack('<B', line)[0]
    if b == 0x00:
        x = ser.read(1)
        x = struct.unpack('<B', x)[0]
        print 'X: %s' % x
    elif b == 0x01:
        y = ser.read(1)
        y = struct.unpack('<B', y)[0]
        print 'Y: %s' % y
    else:
        print b b

This example only uses the joystick, but I've since modified it to read the button presses as well and I will be testing it out on our companies robot this week. The results I've got seem pretty good, there's no noticeable delay between using the joystick and seeing the results in my python script.




No comments:

Post a Comment