Trailblazer Robotics
Unit 1 · Week 1

Your First C++ Program

Open VEXcode IQ in C++ mode, write your first program, and learn what each piece of the code actually does.

You'll learn

Why move from blocks to C++?

Blocks are great for getting started, but every block is just a friendly wrapper around a line of C++. Moving to text gives you three things blocks can't: precise control (write your own algorithms like PID), readability across long programs, and the same skills used in real engineering. The hardest part is the syntax, not the ideas, you already know the ideas from blocks.

Your first program

In VEXcode IQ, create a new C++ project. The editor opens with a template that already does the boring setup for you. You only write code inside main().

#include "vex.h"

// VEXcode IQ generates the lines below for you when you add motors / sensors
// in the Robot Configuration menu. You do not type them yourself.
brain Brain;
motor LeftMotor  = motor(PORT1, false);
motor RightMotor = motor(PORT6, true);   // mounted facing the other way

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();

  // your code starts here
  LeftMotor.spin(forward);
  RightMotor.spin(forward);
  wait(2, seconds);
  LeftMotor.stop();
  RightMotor.stop();
}
What VEXcode IQ does for you: when you add a motor in the "Robot Configuration" sidebar, the IDE writes the motor LeftMotor = motor(PORT1, false); line for you. It also adds the call to vexcodeInit() inside main(), which wires up your sensors and brain at startup. Never delete that line. You write the code after it.

Anatomy of the program

Try it

Modify the program to drive backward for 1 second instead of forward for 2 seconds. Hint: change forward to reverse and the time.

Curated references

Find the Bug

Two programs with intentional errors. Spot the bug.

Problem 1A
This program won't compile. The error message points to line 8. What's missing?
#include "vex.h"
// using namespace vex;  (auto-included by VEXcode IQ)
brain Brain;
motor LeftMotor  = motor(PORT1, false);
motor RightMotor = motor(PORT6, true);

int main() {
  LeftMotor.spin(forward)
  RightMotor.spin(forward);
  wait(2, seconds);
  LeftMotor.stop();
  RightMotor.stop();
}
Problem 1B
This program compiles fine. The robot is supposed to drive straight forward, but instead it spins in place. Why?
motor LeftMotor  = motor(PORT1, false);
motor RightMotor = motor(PORT6, false);

int main() {
  LeftMotor.spin(forward);
  RightMotor.spin(forward);
  wait(2, seconds);
}
← Dashboard Next: Variables →