Skip to content

Programming a Square

  • Lesson
  • 2 min read
  • 2 of 2 in this chapter

Adding initialization code

Initialization is critical to code, even though the robot does not do anything yet. What initialization does is tell what motors should do based on the port and the wiring on the robot. To set up the code to do this, type the following into the space left over from the earlier lesson:

Java
@Override
 public void runOpMode() {
 
 telemetry.addData("Status", "Initialized");
 telemetry.update();
 
 leftDrive = hardwareMap.get(DcMotor.class, "left_drive");
 rightDrive = hardwareMap.get(DcMotor.class, "right_drive");
 
 leftDrive.setDirection(DcMotor.Direction.FORWARD);
 rightDrive.setDirection(DcMotor.Direction.REVERSE);
 
 waitForStart();
 runtime.reset();
 
 }

Adding autonomous instructions for the robot

This is the actual code that moves the robot. This code will be setting motor powers and changing positions. This code will affect the robot in the order it is written. This code, specifically, will make the robot move in the shape of a square. Type the following autonomous code into the space left from the earlier lesson:

Java
waitForStart();
runtime.reset();
 
 // go forward .7 secs
 leftDrive.setPower(power);
 rightDrive.setPower(power);
 sleep(700);
 
 // turn left for .3 secs
 leftDrive.setPower(-power);
 rightDrive.setPower(power);
 sleep(300);
 
 // go forward .7 secs
 leftDrive.setPower(power);
 rightDrive.setPower(power);
 sleep(700);
 
 // turn left for .3 secs
 leftDrive.setPower(-power);
 rightDrive.setPower(power);
 sleep(300);
 
 // go forward for .7 secs
 leftDrive.setPower(power);
 rightDrive.setPower(power);
 sleep(700);
 
 // turn left for .3 secs
 leftDrive.setPower(-power);
 rightDrive.setPower(power);
 sleep(300);
 
 // go forward for .7 secs
 leftDrive.setPower(power);
 rightDrive.setPower(power);
 sleep(700);

The sleep function

The 'sleep' function used frequently in the code above pauses in the code loop for the number of milliseconds specified in the parentheses (). In this case, the 'sleep' function keeps the motors at the power they are set at in the 2 lines before the 'sleep' statement for the time chosen (300 or 700 milliseconds in this case).

Run the square program

In the next lesson, we will be making a basic autonomous program that programs the robot to drive in a square. Running the program is very similar to running a TeleOp. Press the triangle on the left of the screen and select "MyFirstAuton". Then, press INIT, and then the play button. This will run your square program.