Button control


Step 1 /8

Introduction

Buttons are a great way to interact with a program. You can use them as controls for games or menu input. Let’s start by configuring the CodeBug emulator to help us out.

Click on the cog at the top right of CodeBug.

Tick the Show leg controls box.

Click Apply button.

The emulator will show the status of CodeBug’s legs with blue arrows. An arrow pointing towards the leg is an input, away from the leg is an output.


Step 2 /8

Configure leg

To sense the button press, we need to configure CodeBug’s leg 1 to be an input.

Click the cog on your start block.

In the window that appears, tick the checkbox next to leg 1 input/output.

Click the cog again to close the window.


Step 3 /8

Set to input

We want to set leg 1 to an input.

Select the drop down menu next to “leg 1 as” on your start block, and select digital input.


Step 4 /8

If button pressed

We want CodeBug to run different code depending on if a button is pressed. To do this we need an If block and a block that checks the leg is connected to ground (through the button).

From the If menu drag in an if else block and place it in an empty space on your workspace.

From the Inputs/Outputs menu drag a leg grounded block and snap it to your if else block.


Step 5 /8

Conditional code

We need different code to run when the button is pressed. If it is pressed we should get a set pixel block to turn an LED on and otherwise a set pixel block to turn the LED off.

From the 5X5 Display menu, take two set pixel blocks.

Snap them both inside your if else block, one next to do and the other next to else.

Change the last number in set pixel block inside the else section to 0.


Step 6 /8

While loop

Make your code repeat so CodeBug can continuously detect the input.

From the Loops menu, drag a repeat while true loop and snap it onto your start block. Then drag your if else block into this while loop.


Step 7 /8

Run your code

Test that your code works correctly.


Step 8 /8

Download your code

To download your code.