How to Write Robot Classes - Pattonville-Robotics/7856 GitHub Wiki

Overview

The various mechanisms of the robot are each represented as a separate class. Typically, mechanisms on the hardware side utilize either a motor or a servo. We can do the same thing in code, depending on which is used for the mechanism. Each mechanism has its own methods that perform a certain function. These robot classes can then be created as objects in the OpModes, which can carry out those methods.

DCMotor

A DCMotor is more powerful than a servo, but is not as precise. There are two methods that you will need to use with a DCMotor. One of these is getPower(). This takes in a single parameter, which is a double between -1 and 1, inclusive. A negative number will make it turn backwards, a positive number will make it turn forwards, and 0 will cause it to stop. The other method is setDirection(), which takes in a direction, which will most likely either be DcMotorSimple.Direction.FORWARD or DcMotorSimple.Direction.REVERSE. This simply changes the direction that the motor turns.

Servo

A Servo is more precise than a DCMotor, but not as powerful. It has one commonly used method: setPosition(), which takes in a double between 0 and 1, inclusive. Depending on where your Servo has been manually set, you may need to figure out which position is 0 and which position is 1 through testing. Many of these positions will eventually be predefined in our Globals class, so we can simply pass a parameter of Globals.EXAMPLE_POSITION.

Writing a Robot Class

The following steps outline how to write a robot class:

  1. Create a class in robotclasses named after the mechanism.
  2. Create your fields. The type will either be DcMotor or Servo. Give it the same name as the class, but in headless-camel-casing.
  3. Create a constructor that takes in a single parameter: HardwareMap hardwareMap. Inside the constructor, define what your field should link to on the hardware map. This can be done with myFieldName = hardwareMap.dcMotor.get("nameOfDevice") where nameOfDevice is the name of the servo or motor in the config file.
  4. Create each method that you need your mechanism to do. These can vary depending on what mechanism the class is for. For example, if you were to create a method runMotor(), then inside the method, you could write myMotorFieldName.setPower(0.7).

Code Example:

public class Conveyor {
    
    private DcMotor conveyor;

    public Conveyor(HardwareMap hardwareMap) {
        conveyor = hardwareMap.dcMotor.get("conveyorMotorName");
    }

    public void runConveyor() {
        conveyor.setPower(0.7);
    }
    
    public void stopConveyor() {
        conveyor.setPower(0);
    }

}