Debugging code


Step 1 /6

Introduction

Programming can sometimes be tricky with large programs and lots going on. This tutorial shows you how to test and debug your code to make your program run the way you want it to.


Step 2 /6

Sample code

You will notice there is already some code on the workspace, we will debug this code. We want the program to turn a row of LEDs on and off one by one, but it currently doesn’t turn the last LED on.


Step 3 /6

CodeBug Emulator

The CodeBug emulator is great for debugging your code because it allows you to see what your code will make CodeBug do before you load it onto your bug.


Step 4 /6

Emulator controls

You can test your code using the emulator control buttons.

  • Click the Play button on the emulator to start running the code.

  • Click the Pause button to stop the program at a random place.

You will see that the CodeBug emulator displays the state of the emulator for where the program is paused and highlight the current block in the code.

  • Repeatedly click the yellow Step Through button to continue running the code block by block.

You will notice that the last set pixel block does not light up the last LED in the row.


Step 5 /6

Breakpoints

We will now use breakpoints to also find the error in the code.

  • Right click the last set pixel block and select Set Breakpoint.

You will notice this block now contains a symbol to show this breakpoint.

  • Click the Play button on the emulator to start running the code.

The emulator will pause when it executes the block that has the breakpoint. We can see from the emulator that this block has not done what we wanted (lighting up the last LED in the row).


Step 6 /6

Fix the code

Now you can easily see that the problem is that the final set pixel block has an x coordinate of 5 instead of 4.

  • Change the x coordinate of the last set pixel block to 4.

  • Click the Play button on the emulator to start running the code.

Well done, you have successfully debugged the program!