Using Loops#

Using Loops

This tutorial walks you through using the repeat block to drive your robot in a square in VEXcode EXP. By the end, you’ll have a project that repeats the same two blocks four times to complete the square.

If you want your robot to repeat the same action multiple times, like driving in a square, you could keep duplicating the same blocks over and over until they move in the pattern of a square. A simpler way, however, is to use the repeat block within the Logic - Control category.

  1. Attach a drive for block and a turn for block below the when started block.

One side of the square, driving forward then turning right.#
    when started
        drive [forward v] for (200) [mm v] ▶
        turn [right v] for (90) degrees ▶
  1. Attach a repeat block below the when started block.

The repeat block, attached above the drive for and turn for blocks.#
    when started
        repeat (10)
        end
        drive [forward v] for (200) [mm v] ▶
        turn [right v] for (90) degrees ▶
  1. Drag the drive for and turn for blocks inside the repeat block.

The drive for and turn for blocks, now inside the repeat block.#
    when started
        repeat (10)
            drive [forward v] for (200) [mm v] ▶
            turn [right v] for (90) degrees ▶
        end
  1. Select the repeat number and change it to 4, so the blocks inside run once for each side of the square.

Screenshot of the repeat block's number highlighted, set to 4.
  1. Make sure your robot is connected to VEXcode, then select Download to download the project to the Brain.

Screenshot of the VEXcode EXP toolbar with the Download button highlighted.
  1. Select Run to run the project. The robot will drive in a square.

Screenshot of the VEXcode EXP toolbar with the Run button highlighted.

You can also repeat a sequence of actions forever, using the forever block instead of repeat.

The forever block.#
    forever
    end

To break out of a loop, use the break block within a loop, to make the code exit the looping block immediately.

The break block.#
    break