Thursday, December 16, 2010

Callback function

Just a quick bit of code to show how the callback function works - 1+2 to connect, then it starts streaming accelerometer and (if available) motionplus data. Press the home button to end.

I'm using two global variables - loop to keep the main loop running, and callback_active to make sure that when you do press the home button, the loop doesn't terminate while the callback function is doing something (I was getting all sorts of exceptions and segmentation faults before including this).

#!/usr/bin/python

import cwiid

loop = True
callback_active = False

def main():
print "Press 1+2"
wiimote = cwiid.Wiimote()
print "OK"

wiimote.mesg_callback = callback
wiimote.enable(cwiid.FLAG_MESG_IFC | cwiid.FLAG_MOTIONPLUS)
wiimote.rpt_mode = cwiid.RPT_ACC | cwiid.RPT_BTN | cwiid.RPT_MOTIONPLUS

global loop
global callback_active
while loop or callback_active:
# Messages will be sent to callback function
pass

wiimote.disable(cwiid.FLAG_MESG_IFC | cwiid.FLAG_MOTIONPLUS)

#----------------------------------------------------------------------
def callback (mesg_list, time):
global callback_active
callback_active = True
for (message, data) in mesg_list:
if message == cwiid.MESG_ACC:
print data
elif message == cwiid.MESG_MOTIONPLUS:
print data
elif message == cwiid.MESG_BTN:
if data & cwiid.BTN_HOME:
global loop
loop = False
else:
pass
callback_active = False

#----------------------------------------------------------------------
main()

1 comment: