Skip to main content

Lesson 2.2: Setting Up Hardware in init() Before the Match Starts


Context

The init() method is the hardware setup phase. It prevents NullPointerException crashes by ensuring that every motor and sensor object is linked to a physical port on the Control Hub before the match begins. Failure to properly instantiate hardware here will result in the robot failing to respond when the "Play" button is pressed.


What is the init() Method?

The init() method is a callback executed exactly once when the driver presses the "INIT" button on the Driver Station. This is the stage where the program accesses the hardwareMap, a built-in object that acts as a registry for all configured devices.

By using hardwareMap.get(), you associate a Java variable with the specific configuration name assigned in the Robot Controller settings. This is also where you define the initial state of components, such as setting DcMotors to RUN_USING_ENCODER mode.


Annotated Code

@TeleOp(name="Init_Demo")
public class InitDemo extends OpMode {

// Declaring the object variable before initialization
private DcMotor armMotor;

@Override
public void init() {
// Linking the Java variable to the physical Control Hub Port 0
// The string "arm" must match the Hub configuration exactly
armMotor = hardwareMap.get(DcMotor.class, "arm");

// Setting the hardware to a known safe state
armMotor.setPower(0);
telemetry.addData("Hardware", "Arm Motor Map Successful");
}

@Override
public void loop() {}
}

Fill-in-the-Blank Practice

  1. The init() method is executed exactly __________ time(s) when the driver presses the INIT button.
  2. To link a physical motor to a code variable, you must call the __________ method from the hardwareMap object.
  3. Variables for hardware like motors should be declared at the __________ level so they can be accessed by both init() and loop().
Show answers
  1. one (1)
  2. get()
  3. class level (as fields, outside of any method)

Challenge

You need to prepare a Servo named "claw" for the match. Use the init() method to map it and ensure it is ready to move once the match starts.

Unit 2 simulator
Supports `init()`, `init_loop()`, `start()`, `loop()`, and `stop()`.
Reads `@TeleOp`, `@Autonomous`, `@Disabled`, telemetry, and `gamepad1`.
Handles local variables, simple math, `resetRuntime()`, and `getRuntime()`.
Does not execute hardware, `gamepad2`, `else` blocks, or loop structures.
Show answer
private Servo claw;

@Override
public void init() {
claw = hardwareMap.get(Servo.class, "claw_servo");
telemetry.addData("Status", "Claw Initialized");
}

Ready to move on?

Sign in with Google to save your progress with Telemark, or continue without saving.