test with PID control to screen on your computer
Dependencies: Motor_with_encoder MODSERIAL QEI mbed
Fork of Project_motor by
main.cpp
- Committer:
- vera1
- Date:
- 2017-10-13
- Revision:
- 8:aff2a7d5861a
- Parent:
- 5:05d09e921b5d
File content as of revision 8:aff2a7d5861a:
#include "mbed.h" #include "MODSERIAL.h" #include "encoder.h" // this program can turn the motor clockwise or counterclockwise depending on the value p or n typed into the terminal. with 's' you can stop the motor MODSERIAL pc(USBTX,USBRX); PwmOut motorspeed(D6); PwmOut motorspeed2(D5); DigitalOut motorposition2(D4); DigitalOut motorposition(D7); DigitalOut led1(D8); DigitalOut led2(D11); AnalogIn pot(A1); AnalogIn pot2(A2); DigitalIn button1(D13); DigitalIn button2(D12); Ticker potmeterreadout; Ticker encoderreadout; Encoder motor1(PTD0,PTC4); // motor 1 is from encoder, otherwise it would be a pain in the ass to change all that code to motorencoder float PwmPeriod = 0.0001f; const double M1_TS = 0.01f; // timestep const double M1_KP = 0.216, M1_KI = 1.8, M1_KD = 0.0; // controller gains for motor 1 double m1_err_int = 0, m1_prev_err = 0; // initiallize errors // PID controller function double PI(double e, const double Kp, const double Ki, const double Kd, double Ts, double&e_int){ //double e_der = (e - e_prev)/Ts; // derivative //e_der = biquad(e_der, f_v1, f_v2, f_a1, f_a2, f_b0, f_b1, f_b2); //e_prev = e; e_int = e_int + Ts*e; // integral return Kp*e + Ki*e_int; //PI controller } volatile float position = 0.0; void readpot(){ position = motor1.getPosition()/4200.00*6.28; float motorpi = PI(reference - position, M1_KP, M1_KI, M1_KD, M1_TS, m1_err_int); pc.printf("PI output = %f, reference = %i\n\r", motorpi, reference); //motorspeed = motorpi; } int main() { float reference = 0.0; pc.baud(9600); potmeterreadout.attach(readpot,0.2f); motorspeed2.period(PwmPeriod); //float motorspeed = 0.0f; while (true) { reference = 0.0; wait(2.0f); reference = 1.0; wait(5.0f); } }