Can't figure out how to have timed motor running alongside drivetrain

So I’m trying to get a motor to run for our hatch panel mechanism on a timer, so when I press a button it lowers and raises, and the code for this is in a separate method. But, whenever I try and get the code to add a delay between starting and stopping the motor using either the Timer.delay() or Thread.sleep(), the drivetrain stops as well. I’ve tried creating other threads, but those have the same problem. Is there a better way to do this that I’m missing?

package frc.robot;

import java.util.concurrent.TimeUnit;

import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX;
import edu.wpi.first.wpilibj.Timer;

public class HatchMechanism implements Runnable {
    WPI_TalonSRX hatchTalon;
    boolean raised;
    static final double waitTime = 0.8;
    Timer hatchTimer = new Timer();

    public HatchMechanism(WPI_TalonSRX hatchTalonInput){
        hatchTalon = hatchTalonInput; // takes the input talon and allows it to work in here
        if(true){
            raised = true;
        }
    }

    public void run () { // changed this to run for the new thread
        if(!raised){
            hatchTalon.set(ControlMode.PercentOutput, 0.8);
            Timer.delay(waitTime);
            hatchTalon.set(ControlMode.PercentOutput, 0);
            raised = !raised;
        }
        else if(raised){
            hatchTalon.set(ControlMode.PercentOutput, -0.8);
            Timer.delay(waitTime);
            hatchTalon.set(ControlMode.PercentOutput, 0);
            raised= !raised;
        }
    }
}
HatchMechanism hatchMech = new HatchMechanism(hatchTalon);
Thread t = new Thread(hatchMech);

this is in the Robot class, while my t.start() is in the Teleop init, and hatchMech.run() is in a method in teleopPeriodic to check for the button being pressed.

Use command-based programming: http://wpilib.screenstepslive.com/s/currentCS/m/java/c/88893

As a rule, you should never use Timer.delay() or Thread.sleep in a robot program.

4 Likes

That looks like it’s gonna work. Thanks for the help.

I’m going to second this real quick, as it is an honest and common mistake for newer programmers, you want your robot to always be responding to inputs and updating outputs, and it can’t do that if you sleep/delay the program execution. Utilize either the Command-Based Structure, or Control Logic (such as a Finite State Machine, or tracking execution time as part of your system’s loop) to manage your actions.