Science Oxford Logo

Use the Joystick's Buttons

Currently, your code sends information to the robot when you push the stick, and doesn't use the 6 buttons.

To add these in, you will need to edit the joystick code, and the robot code.


Pressing Button A

Open your joystick code, and look at your while True loop.

The first line tells the micro:bit to look at the stick, we need to add in another line underneath it, to look at the buttons as well.

Edit your code (don't delete or repeat any of it) to look like this:

while True:
        joystick = joystick_push()

        button = button_press()

        instructions = str(joystick[0]) + " " + str(joystick[1])
        print(instructions)
        sleep(10)
        radio.send(instructions)

Now you need to tell the code:

This means adding in some new code, and changing the indentation:

while True:
        joystick = joystick_push()
        button = button_press()

        if button == 'A':
            radio.send('A')
            sleep(100)

        else:
            instructions = str(joystick[0]) + " " + str(joystick[1])
            print(instructions)
            sleep(10)
            radio.send(instructions)

Look carefully at the example code - which parts are the same, and which parts are new?

Indentation is very important! Test your code to check for errors, and see what happens to your robot when you press the joystick's 'A' button.


Responding to Button A

Does your robot show you a happy face when you press the joystick's 'A' button?

This is because the robot's code has the following instructions in it:

if instructions == 'A':
        display.show(Image.HAPPY)

What do you want to happen? You can edit this code (lines 79-80) to make something different happen when you press 'A' on your joystick.

Only change the display.show(Image.HAPPY) line, and be careful of your indention!

Remember to test your code carefully before making any more changes.


Adding the rest of the buttons

Once you have Button A working the way you like, you can add in the other buttons!

To change the joystick code, you will add in even more code, in the middle of what you have done before.

The code below shows you buttons A & B - follow the same structure to add in C, D, E & F, then switch to your robot's code to edit how it will respond.

while True:
        joystick = joystick_push()
        button = button_press()

        if button == 'A':
            radio.send('A')
            sleep(100)

        elif button == 'B':
            radio.send('B')
            sleep(100)

        else:
            instructions = str(joystick[0]) + " " + str(joystick[1])
            radio.send(instructions)
            sleep(10)

A complete working example of the joystick code can be downloaded here.