PD Control for KL05Z

Dependencies:   QEI mbed

main.cpp

Committer:
benkatz
Date:
2013-09-02
Revision:
2:f84a70291ac8
Parent:
1:8ff6c7474d95
Child:
3:f169c357a44d

File content as of revision 2:f84a70291ac8:

#include "mbed.h"
#include "QEI.h"  //QEI is a quadrature encoder library
#define pi  3.14159265358979323846


//create a new quadrature encoder object
QEI encoder(p25, p26, NC, 1200, QEI::X4_ENCODING);       //(encoder channel 1 pin, encoder channel 2 pin, index (n/a here), counts per revolution, mode (X4, X2))

Ticker SampleFrequency;

//Values that will be used for the PID controller

int steps_per_rev = 1200; //Encoder CPR * gear ratio
float position = 0;
float error = 0;
float old_error = 0;
float goal_position = 0;
float p_gain = 0;
float d_gain = 0;
float sample_period = .0004;
float command = 0;

//

float pulsesToRadians(float pulses) //Encoder steps to revolutions of output shaft in radians
{
    return ((pulses/steps_per_rev)*(2*pi));
}


void updateCommand(void){
    
    position = pulsesToRadians(encoder.getPulses());        //use the getPulses functin to read encoder position, convert value to radians
    old_error = error;                                      
    error = position - goal_position;
    command = p_gain*error + d_gain*sample_period*(error-old_error);    //modify the command based on position feedback
    
    
}





int main() {
    

    SampleFrequency.attach(&updateCommand, sample_period);        //Encoder will be sampled at 2.5 kHz
    
    while(1) {
        
    }
}