first draft

Dependencies:   PID mbed

Fork of EE192_PID by Ollie Peng

Committer:
openg
Date:
Tue Mar 15 21:44:34 2016 +0000
Revision:
1:5c1051bb7958
Parent:
0:87a63b2d26ef
first draft;

Who changed what in which revision?

UserRevisionLine numberNew contents of line
openg 0:87a63b2d26ef 1 #include "mbed.h"
openg 0:87a63b2d26ef 2
openg 0:87a63b2d26ef 3 Serial pc(USBTX, USBRX); // tx, rx
openg 0:87a63b2d26ef 4 PwmOut Clock(PTD4);
openg 0:87a63b2d26ef 5 PwmOut Output(////);
openg 0:87a63b2d26ef 6 AnalogIn Sensor(////);
openg 0:87a63b2d26ef 7
openg 0:87a63b2d26ef 8 float adjustmentFactor = 1.0; //change so that sensor data is calibrated
openg 0:87a63b2d26ef 9 float ref = 3.0;
openg 0:87a63b2d26ef 10 float error = 0.0;
openg 0:87a63b2d26ef 11 float totalError = 0.0;
openg 0:87a63b2d26ef 12 int period = 1000;
openg 0:87a63b2d26ef 13 int PW = period/2;
openg 0:87a63b2d26ef 14
openg 0:87a63b2d26ef 15 int outPeriod = period; //assume period always is the same
openg 1:5c1051bb7958 16 int outPW = outPeriod/2;
openg 0:87a63b2d26ef 17
openg 0:87a63b2d26ef 18 float Ki = 0; //adjust
openg 0:87a63b2d26ef 19 float Kp = 30; //adjust
openg 0:87a63b2d26ef 20
openg 0:87a63b2d26ef 21 Ticker Controller;
openg 1:5c1051bb7958 22 int flag = 0;
openg 0:87a63b2d26ef 23
openg 0:87a63b2d26ef 24 void Control(){
openg 0:87a63b2d26ef 25 error = ref - Sensor.read()*adjustmentFactor;
openg 0:87a63b2d26ef 26 totalError += error;
openg 1:5c1051bb7958 27 outPW = Kp*error + Ki*totalError;
openg 0:87a63b2d26ef 28 Output.period_us(outPeriod);
openg 1:5c1051bb7958 29 Output.pulsewidth_us(int(outPW));
openg 1:5c1051bb7958 30 flag = 1;
openg 0:87a63b2d26ef 31 }
openg 0:87a63b2d26ef 32
openg 0:87a63b2d26ef 33 int main() {
openg 0:87a63b2d26ef 34 Clock.period_us(period);
openg 0:87a63b2d26ef 35 Clock.pulsewidth_us(PW);
openg 0:87a63b2d26ef 36 Controller.attach_us(Control,period*128); //assumed that we should wait 128 clock cycles before activating controller
openg 0:87a63b2d26ef 37 //because line camera requires 128 cycles. should verify
openg 0:87a63b2d26ef 38
openg 1:5c1051bb7958 39 while(1) {
openg 1:5c1051bb7958 40 if (flag) {
openg 1:5c1051bb7958 41 pc.printf("PW: %d \n\r",outPW);
openg 1:5c1051bb7958 42 flag = 0;
openg 1:5c1051bb7958 43 }
openg 1:5c1051bb7958 44 }
openg 1:5c1051bb7958 45
openg 0:87a63b2d26ef 46 }