PI controller to make the motor follow pot1
Dependencies: HIDScope MODSERIAL QEI mbed
Fork of PI_control_pot by
Diff: main.cpp
- Revision:
- 0:dbe7715dcfe9
- Child:
- 1:b75c4b9f1c98
diff -r 000000000000 -r dbe7715dcfe9 main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Thu Sep 24 15:30:24 2015 +0000 @@ -0,0 +1,103 @@ +#include "mbed.h" +#include "QEI.h" +#include "HIDScope.h" + +//info uit +HIDScope scope(3); + +//encoders +QEI encoder1 (D12,D13,NC,32); // first b then a for clockwise + + +//ingangen +AnalogIn pot1(A2); + +//uitgangen +DigitalOut motor1_direction(D7);// draairichting motor 1 (1 is CW encoder als je daar op kijkt en CW shaft als je daar op kijkt) +PwmOut motor1_speed_control(D6);//aanstuursnelheid motor 1 +//PwmOut motor2_speed_control(D5); +//DigitalOut motor2_direction(D4); +const int CW=1; //clockwise +const int CCW=0; //counterclockwise + +//frequencies +//const float pwm_frequency=1000; +const double hidscope_frequency=100; +const double p_control_frequency=5; + +//tickers +Ticker hidscope_ticker; +Ticker p_control_ticker; + +//constants +const int cpr=32*131; +const float PI=3.1415; +const float counttorad=((2*PI)/cpr); +const float motor1_p_kp=0.5; + +//go flags +volatile bool scopedata_go=false, p_control_go=false; + +//acvitator functions + +void scopedata_activate() +{ + scopedata_go=true; +} +void p_control_activate() +{ + p_control_go=true; +} +///////////////////////////////////////////////////////FUNCTIONS////////////////////////////////////////////////////////////////////////// + +//scopedata +void scopedata() +{ + scope.set(0,2*PI*pot1.read());//gewenste hoek in rad van potmeter + scope.set(1,counttorad*encoder1.getPulses());//hoek in rad van outputshaft + scope.set(2,motor1_speed_control.read());//pwm signaal naar motor toe + scope.send(); +} + +//re usable P controller +double p_control(float error,float kp) +{ + return (error*kp); +} + +int main() +{ + //set initial shizzle + //motor1_speed_control.period(1.0/pwm_frequency); + motor1_speed_control.write(0); + + //tickers + hidscope_ticker.attach(&scopedata_activate,1.0/hidscope_frequency); + p_control_ticker.attach(&p_control_activate,1.0/p_control_frequency); + + while(1) { + //control motor 1 with a p controller + if (p_control_go==true) { + float signal_motor1=p_control(2*PI*pot1.read()-counttorad*encoder1.getPulses(),motor1_p_kp);//send error to p controller + if (signal_motor1>=0) {//determine CW or CCW rotation + motor1_direction.write(CW); + } else { + motor1_direction.write(CCW); + } + + if (fabs(signal_motor1)>=1) { //check if signal is <1 + signal_motor1=1;//if signal >1 make it 1 to not damage motor + } else { + signal_motor1=fabs(signal_motor1);// if signal<1 use signal + } + + motor1_speed_control.write(fabs(signal_motor1));//write signal to motor + p_control_go=false; + } + //call scopedata + if (scopedata_go==true) { + scopedata(); + scopedata_go=false; + } + } + return 0; +}