control flow doet nog niks

Dependencies:   Encoder HIDScope MODSERIAL mbed

main.cpp

Committer:
Zeekat
Date:
2015-10-09
Revision:
3:7273bbe6aa02
Parent:
2:2563df4ee829
Child:
4:072b99947fc6

File content as of revision 3:7273bbe6aa02:

#include "mbed.h"
#include "MODSERIAL.h"
#include "encoder.h"
#include "HIDScope.h"

Serial pc(USBTX,USBRX);
HIDScope scope(2);          // definieerd het aantal kanalen van de scope

// Define Tickers and control frequencies
Ticker          controller1, controller2;        // definieer de ticker die controler1 doet
    // Go flag variables
    volatile bool motor1_go = false, motor2_go = false;

    // Frequency control
    double controlfreq = 50 ;    // controlloops frequentie (Hz)
    double controlstep = 1/controlfreq; // timestep derived from controlfreq


//MOTOR OUTPUTPINS
// motor 1
    PwmOut motor1_aan(D6);      // PWM signaal motor 2 (uit sheets)
    DigitalOut motor1_rich(D7); // digitaal signaal voor richting
// motor 2
    PwmOut motor2_aan(D5);
    DigitalOut motor2_rich(D4);

// ENCODER INPUTPINS
Encoder motor1_enc(D12,D11);        // encoder outputpins
Encoder motor2_enc(D10,D9);

int reference1 = 0;         // set the reference position of the encoders
int reference2 = 0;


// EXTRA INPUTS AND REQUIRED VARIABLES
//POTMETERS
    AnalogIn potright(A0);      // define the potmeter outputpins
    AnalogIn potleft(A1);

// RESETBUTTON              
    DigitalIn   button(PTA4);      // defines the button used for a encoder reset
    int button_pressed = 0;


// REFERENCE SIGNAL SETTINGS
    // Define signal amplification  (needed with EMG, used in control loop, precise amp determination is a work in progress!!!!)    ??
    double signalamp1 = 1;
    double signalamp2 = 1;
// Define gain and offset of the input(input between 0 and 1 is optimized). For EMG use 0, 1 and false, for POT use 0.5, 2 and true
    double offset = 0.5;
    double gain = 2; 
    bool POT_in = true;     // show potmeter is attached, increases the range for which 0 is the output.
// Define storage variables for reference values
    double c_reference1 = 0;
    double c_reference2 = 0;
// Define the maximum rate of change for the reference (velocity)
    double Vmax = 5;            // rad/sec

// CONTROLLER SETTINGS
    // motor 1
    const double m1_Kp = 1;         // Proportional constant     
    const double m1_Ki = 1;         // integration constant
    const double m1_Kd = 0;         // differentiation constant
    // motor 2
    const double m2_Kp = 1;
    const double m2_Ki = 0;
    const double m2_Kd = 0;
// storage variables
    // motor 1
    double m1_err_int = 0; 
    double m1_prev_err = 0;
    // motor 2
    double m2_err_int = 0;
    double m2_prev_err = 0;


//// FILTER VARIABLES
// storage variables
        // differential action filter, same is used for both controllers
        double m_f_v1 = 0;
        double m_f_v2 = 0;

// Filter coefficients
        // differential action filter
        const double m_f_a1 = 1.0, m_f_a2 = 2.0, m_f_b0 = 1.0, m_f_b1 = 3.0, m_f_b2 = 4.0;      // coefficients from sheets are used as first test.



////////////////////////////////////////////////////////////////
/////////////////// START OF SIDE FUNCTIONS ////////////////////
//////////////////////////////////////////////////////////////
// these functions are tailored to perform 1 specific function


// counts 2 radians
// this function takes counts from the encoder and converts it to the amount of radians from the zero position. 
// It has been set up for standard 2X DECODING!!!!!!
double get_radians(double counts)       
{
    double pi = 3.14159265359;
    double radians = (counts/4200)*2*pi;        // 2X DECODING!!!!! ((32 counts/rotation, extra warning)
    return radians;
}


// This functions takes a 0->1 input converts it to -1->1 and uses passing by reference (&c_reference)
// to create a reference that moves with a variable speed. It is now set up for potmeter values.  
double reference_f(double input, double &c_reference)
{
    double  potset = (input-offset)*gain;
    if(POT_in == true && potset < 0.1 && potset > -0.1) // larger area for potmeter to get a zero value
    { 
        potset = 0;
    }
    double reference = c_reference + potset * controlstep * Vmax ;
           c_reference = reference; // change the global variable to the latest location.
    return reference;
}


// This function takes the controller outputvalue and ensures it is between -1 and 1
// this is done to limit the motor input to possible values (the motor takes 0 to 1 and the sign changes the direction).
// needs more work to use it for the wind-up prevention.
double outputlimiter (double output, double limit)
{
    if(output> limit)                                
    {
        output = 1;
    }
    else if(output < limit && output > 0)
    {
        output = output;
    }
    else if(output > -limit && output < 0)
    {
        output = output;
    }
    else if(output < -limit)
    {
        (output = -1);
    }
    return output;
}


// BIQUADFILTER CODE GIVEN IN SHEETS 
// used for d-control
double biquadfilter(double u, double &v1, double &v2, const double a1, const double a2, const double b0, const double b1, const double b2)
{
    double v = u - a1*v1 - a2*v2;
    double y = b0*v + b1*v1 + b2*v2;
    v2 = v1;
    v1 = v;
    return y;
    }


// PID Controller given in sheets
// aangepast om zelfde filter te gebruiken en om de termen later gesplitst te kunnen limiteren (windup preventie!!)
double PID(double e, const double Kp, const double Ki, const double Kd, double Ts,double &e_int, double &e_prev)
{
// Proportional
double P = Kp * e;
pc.printf("P = %f, ",P);
// Integral
e_int = e_int + Ts * e;
double I = e_int * Ki;
pc.printf("I = %f, ",I);
// Derivative   (Disabled for now because of NaN problem from filter
double e_derr = (e - e_prev)/Ts;
pc.printf("e_derr %f, ",e_derr);
e_derr = biquadfilter(e_derr, m_f_v1, m_f_v2, m_f_a1, m_f_a2, m_f_b0, m_f_b1, m_f_b2);
pc.printf("fil_e_derr %f, ",e_derr);    // check for NaN                ??
e_prev = e;
// double D = Kd* e_derr;

// PID
double output = P + I ;// + D;
return output;
}



// this function is a simple K control called by the motor function
double K_control(double error,double K)
{
    double output = K*error;                            // controller output K*e
    output = outputlimiter(output,1);             // limit the output to -1->1
    return output;
}

/////////////////////////////////////////////////////////////////////
////////////////// PRIMARY CONTROL FUNCTIONS ///////////////////////
///////////////////////////////////////////////////////////////////
// these functions are used to control all aspects of a single electric motor and are called by the main function

// MOTOR 1
void motor1_control()
{
    double input1 = potright.read()*signalamp1;
    double reference1 = reference_f(input1, c_reference1);      // determine the reference that has been set by the inputsignal
    double rads1 = get_radians(motor1_enc.getPosition());    // determine the position of the motor
    double error1 = (reference1 - rads1);                       // determine the error (reference - position)
    scope.set(0,reference1);
    scope.set(1,rads1);
    scope.send();   
    double output1 = PID(error1, m1_Kp, m1_Ki, m1_Kd, controlstep, m1_err_int, m1_prev_err);
    pc.printf("output 1 %f \n",output1);
  
    // ws best locatie om output te blokkeren als grenzen bereikt zijn, simpel if-loopje met rad1
    
    if(output1 > 0) {                    // uses the calculated output to determine the direction  of the motor
        motor1_rich.write(0);
        motor1_aan.write(output1);
    } else if(output1 < 0) {
        motor1_rich.write(1);
        motor1_aan.write(abs(output1));
    }
}

// MOTOR 2
void motor2_control()
{
    double input2 = potleft.read()*signalamp2;
    double reference2 = reference_f(input2, c_reference2);      // determine the reference that has been set by the inputsignal
    double rads2 = get_radians(motor2_enc.getPosition());    // determine the position of the motor
    double error2 = (reference2 - rads2);                       // determine the error (reference - position)
    // scope.set(3,reference2);                                         
    // scope.set(4,rads2);
    // scope.send();
    
    double output2 = PID(error2, m2_Kp, m2_Ki, m2_Kd, controlstep, m2_err_int, m2_prev_err);
    if(output2 > 0) {                    // uses the calculated output to determine the direction  of the motor
        motor2_rich.write(0);
        motor2_aan.write(output2);
    } else if(output2 < 0) {
        motor2_rich.write(1);
        motor2_aan.write(abs(output2));
    }
}


//////////////////////////////////////////////////////////////////
//////////// DEFINE GO-FLAG FUNCTIONS ///////////////////////////
////////////////////////////////////////////////////////////////

void motor1_activate()
{ 
    motor1_go = true; 
}
 
void motor2_activate()
{ 
    motor2_go = true; 
}

int main()
{
    pc.baud(115200);
    // Ticker calling the primary functions. If neccessary use the ticker to change bools and execute in the main loop as shown in the sheets.
    controller1.attach(&motor1_activate, controlstep);
    // controller2.attach(&motor2_activate, controlstep);   Disabled while debugging PID-controller
    while(true) 
    {
        if(motor1_go)
        {
            motor1_go = false;
            motor1_control();
        }
        if(motor2_go)
        {
            motor2_go = false;
            motor2_control();
        }
        if(button.read() == button_pressed)             // reset the encoder to reference position
        {
            motor1_enc.setPosition(reference1);
            motor2_enc.setPosition(reference2);
        }
    }
}