javamultithreadingasynchronouspid-controller

How can I implement a multi-threaded PID controller in Java?


I'm kinda new to Java, so haven't yet fully grasped the concept of multithreading.I would like to create a PIDController class that allows me to do this:

ControllerMethods methods = new ControllerMethods()
                            {
                                public long getError(long setpoint)
                                {
                                    //get an input
                                }
                                public void setOutput(long value)
                                {
                                    //do something
                                }
                                public void isComplete(long setpoint)
                                {
                                    return getError() == 0;
                                }
                            };

PIDController motorPID = new PIDController(setpoint, kp, ki, kd, methods);

motorPID.run();
//runs the PID controller to completion (methods.isComplete() == true)

motorPID.run(false);
//starts the PID controller in a separate thread, allowing
//continual monitoring in the current thread

while(motorPID.isRunning())
{
    //do something else
    if(condition1)
        motorPID.pause();
        //pause the PID controller, preventing the integral from increasing
    else if(condition2)
        motorPID.stop();
}

I've worked out how to calculate the standard PID argorithms, but I can't work out how to provide the asynchronous functionality.

Can anybody tell me how I can achieve a similar API?


Solution

  • You already implemented a run() method for PIDController so you should also implement the Runnable interface:

    class PIDController implements Runnable {
        ....
    }
    

    Now you can start your PIDController asynchonous, by calling:

    pidControllerThread = new Thread( pidController );
    pidControllerThread.start();
    

    For synchronization (if needed) you should have a look at the sun concurrency guide.