Script voor aansturen motoren
Dependencies: Encoder HIDScope MODSERIAL mbed-dsp mbed
main.cpp
- Committer:
- jessekaiser
- Date:
- 2014-10-22
- Revision:
- 4:db3dad7e53e3
- Parent:
- 3:dcc4cebba0d7
- Child:
- 5:e4b9cc904928
File content as of revision 4:db3dad7e53e3:
#include "mbed.h" #include "encoder.h" #include "HIDScope.h" #define TSAMP 0.01 #define K_P (0.1) #define K_I (0.03 *TSAMP) #define K_D (0.001 /TSAMP) #define I_LIMIT 1. #define M1_PWM PTC8 //blauw #define M1_DIR PTC9 //groen #define M2_PWM PTA5 //blauw #define M2_DIR PTA4 //groen Serial pc(USBTX, USBRX); DigitalOut led1(LED_RED); void clamp(float * in, float min, float max); float pid(float setpoint, float measurement); volatile bool looptimerflag; HIDScope scope(6); void setlooptimerflag(void) { looptimerflag = true; } int main() { //Let op dat de jumpers goed staan als het motortje niet wilt draaien. De E1 jumper moet onder de nummer 7 pin. De locatie van de M1 pin //bepaalt of de motor CW of CCW draait. //start Encoder-> first pin should be PTDx or PTAx, second pin doesn't matter //motor 25D Encoder motor1(PTD3,PTD5); //wit, geel PwmOut pwm_motor1(M2_PWM); // PTC8, blauw, /*PwmOut to motor driver*/ pwm_motor1.period_us(75); //10kHz PWM frequency DigitalOut motordir1(M2_DIR); //PTC9, groen //motor2 37D Encoder motor2(PTD2, PTD0); //wit, geel PwmOut pwm_motor2(M1_PWM); //PTA5, blauw pwm_motor2.period_us(75); DigitalOut motordir2(M1_DIR); //PTA4, groen char c ='0'; while(1) { pwm_motor1.write(1); motordir1.write(1); do { if(pc.readable()) { c = pc.getc(); } } while((c !='1')); { c = '0'; pwm_motor1.write(0.5); motordir1.write(0); wait(3); } } } //clamps value 'in' to min or max when exceeding those values //if you'd like to understand the statement below take a google for //'ternary operators'. void clamp(float * in, float min, float max) { *in > min ? *in < max? : *in = max: *in = min; } float pid(float setpoint, float measurement) { float error; static float prev_error = 0; float out_p = 0; static float out_i = 0; float out_d = 0; error = setpoint-measurement; out_p = error*K_P; out_i += error*K_I; out_d = (error-prev_error)*K_D; clamp(&out_i,-I_LIMIT,I_LIMIT); prev_error = error; scope.set(1,out_p); scope.set(2,out_i); scope.set(3,out_d); return out_p + out_i + out_d; }