Monday, December 6, 2010

Accelerometer data

Thanks to this web site and this forum posting, I've got accelerometer data from the wiimote. I've also found out how to check button presses.

The program below buzzes (rumbles) the wiimote when the connection is made. After that:

  • The A and B buttons print "A" and "B" to the screen.
  • The + button starts the display of accelerometer data, and the - button stops this display.
  • The 1 button starts the buzzer, and the 2 button stops it.
  • The 4-way button at the top changes the state of the four LEDs at the bottom.
  • The home button ends the program.



#!/usr/bin/python

import cwiid
from time import sleep

print "Press 1+2 on the Wiimote now"

w = cwiid.Wiimote()
# Rumble to indicate a connection
w.rumble = 1
print "Connection established"
sleep(0.2)
w.rumble = 0

w.enable(cwiid.FLAG_MESG_IFC)
w.rpt_mode = cwiid.RPT_ACC | cwiid.RPT_BTN

loop = True
show_accelerometers = False
last_accelerometers = (0, 0, 0)
led_status = 0

while (loop):
sleep(0.01)
messages = w.get_mesg()
for mesg in messages:
# Accelerometer:
if mesg[0] == cwiid.MESG_ACC:
if show_accelerometers:
accelerometers = mesg[1]
if accelerometers != last_accelerometers:
print accelerometers
last_accelerometers = accelerometers
# Button:
elif mesg[0] == cwiid.MESG_BTN:
if mesg[1] & cwiid.BTN_HOME:
loop = False
if mesg[1] & cwiid.BTN_PLUS:
show_accelerometers = True
if mesg[1] & cwiid.BTN_MINUS:
show_accelerometers = False
if mesg[1] & cwiid.BTN_1:
w.rumble = 1
if mesg[1] & cwiid.BTN_2:
w.rumble = 0
if mesg[1] & cwiid.BTN_UP:
led_status = led_status ^ 0x01
w.led = led_status
if mesg[1] & cwiid.BTN_DOWN:
led_status = led_status ^ 0x02
w.led = led_status
if mesg[1] & cwiid.BTN_LEFT:
led_status = led_status ^ 0x04
w.led = led_status
if mesg[1] & cwiid.BTN_RIGHT:
led_status = led_status ^ 0x08
w.led = led_status
if mesg[1] & cwiid.BTN_A:
print "A"
if mesg[1] & cwiid.BTN_B:
print "B"
else:
print mesg

No comments:

Post a Comment