Skip to content

Instantly share code, notes, and snippets.

@nealtodd
Last active December 17, 2015 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nealtodd/5587509 to your computer and use it in GitHub Desktop.
Save nealtodd/5587509 to your computer and use it in GitHub Desktop.
Test of connecting Wiimotes to a Raspberry Pi via Bluetooth. Reports button presses from a Wiimote. Couched in a trivial little game for two kids to 'remote control' each other: The sender can use the crosspad to light the leds on the receiver. The receiver walks in the direction indicated on the leds (led1 = turn left, led2 = forwards, led3=bac…
import time
import cwiid
class Wiible():
buttons = [
"BTN_2",
"BTN_1",
"BTN_B",
"BTN_A",
"BTN_MINUS",
"BTN_HOME",
"BTN_LEFT",
"BTN_RIGHT",
"BTN_DOWN",
"BTN_UP",
"BTN_PLUS"
]
led_mapping = {
"BTN_LEFT": 1,
"BTN_UP": 2,
"BTN_DOWN": 4,
"BTN_RIGHT": 8,
}
def __init__(self, wm_sender, wm_receiver, sample_freq=2):
self.wm_sender, self.wm_receiver = wm_sender, wm_receiver
self.wm_sender.rpt_mode, self.wm_receiver.rpt_mode = cwiid.RPT_BTN, cwiid.RPT_BTN
self.sample_freq = sample_freq
def play(self):
self._start()
while True:
self.wm_receiver.led = 0
buttons_pressed = []
for button in self.buttons:
if self.wm_sender.state['buttons'] & getattr(cwiid, button):
buttons_pressed.append(button)
if buttons_pressed:
print buttons_pressed
led = 0
for button in buttons_pressed:
led += self.led_mapping.get(button, 0)
self.wm_receiver.led = led
self.wm_receiver.rumble = len(set(buttons_pressed).intersection(set(['BTN_A', 'BTN_B'])))
if 'BTN_MINUS' in buttons_pressed:
self.wm_sender, self.wm_receiver = self.wm_receiver, self.wm_sender
print "Switched control"
if 'BTN_HOME' in buttons_pressed:
break
time.sleep(1. / self.sample_freq)
self._end()
def _start(self):
for led in xrange(0, 4):
self.wm_sender.led, self.wm_receiver.led = 2**led, 2**led
self.wm_sender.led, self.wm_receiver.led = 0, 0
self._pulse_rumble(0.25, receiver=False)
print "2 Up"
def _end(self):
for _ in xrange(0, 2):
self._pulse_rumble(0.25)
print "Game over"
def _pulse_rumble(self, duration, sender=True, receiver=True):
self.wm_sender.rumble, self.wm_receiver.rumble = True & sender, True & receiver
time.sleep(duration)
self.wm_sender.rumble, self.wm_receiver.rumble = False, False
# 1+2 on Wiimote 1 to pair
wm1 = cwiid.Wiimote()
# 1+2 on Wiimote 2 to pair
wm2 = cwiid.Wiimote()
game = Wiible(wm1, wm2)
game.play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment