Search code examples
pythonledwiimote

Python exitting loop with Wiimote button press


I'm writing a python script that will control LEDs with a Wiimote using the cwiid library. The program recognizes the wiimote and is able to start the loops, but it will not let me stop the loop when the user presses "B" on the remote. Here is the relevant code, and I can provide the rest of the script if needed. Thanks.

  buttons = wii.state['buttons']

...

  if (buttons & cwiid.BTN_A):
    print 'Button A pressed'
    print 'Press B to cancel loop'
    keepRunning = True
    while keepRunning:
        blink(32)#5v green
        blink(38)#5v yellow
        blink(36)#5v blue
        blink(40)#5v red
        blink(37)#3v3 green
        blink(35)#3v3 yellow
        blink(33)#3v3 blue
        blink(31)#3v3 red
        if (buttons & cwiid.BTN_B):
            keepRunning  = False
    time.sleep(button_delay)

Here is the fixed loop per Stuart's answer

  if (buttons & cwiid.BTN_A):
    print 'Button A pressed'
    print 'Press B to cancel loop'
    keepRunning = True
    while keepRunning:
        blink(32)#5v green
        blink(38)#5v yellow
        blink(36)#5v blue
        blink(40)#5v red
        blink(37)#3v3 green
        blink(35)#3v3 yellow
        blink(33)#3v3 blue
        blink(31)#3v3 red
        buttons = wii.state['buttons']#added in this line
        if (buttons & cwiid.BTN_B):
            keepRunning  = False
    time.sleep(button_delay)

Solution

  • wii.state['buttons'] appears to be a number, so storing it in the variable buttons means it is no longer updated when the user presses a different combination of buttons.

    To fix this just replace buttons with a direct reference to wii.state['buttons'] each time.

    You might want to consider checking whether B is pressed after each blink, like this:

    from itertools import cycle
    ...
    if wii.state['buttons'] & cwiid.BTN_A:
        print 'Button A pressed'
        print 'Press B to cancel loop'
        for colour in cycle([32, 38, 36, 40, 37, 35, 33, 31]):
            blink(colour)
            if wii.state['buttons'] & cwiid.BTN_B:
                break
        time.sleep(button_delay)