Andreas Steffen / Mbed 2 deprecated PIservo

Dependencies:   mbed

main.cpp

Committer:
Reignbow
Date:
2012-08-06
Revision:
1:dc799997391e
Parent:
0:3e6ae21a6bb1
Child:
2:6d472c554758

File content as of revision 1:dc799997391e:

/* PIservo
 implement a PI controller with USB serial gain setting to stabilize dipole trap power.
 Two analog inputs (control and sensor), one analog output (to RF VCA).

20120806 Andreas Steffen
*/


#include "mbed.h"

DigitalOut adcCS(p8);
AnalogOut vca(p18);
SPI adcSPI(p5,p6,p7); //talk to ad7921
Serial pc(USBTX, USBRX);


Timer t;
Ticker commTick;
Ticker intTick;

float pGain = 0.5;
float iGain = 5000.;
float integrator = 0; //the building up integrator value

//for keeping track of the cycle rate
float cycT=0;  
float cycN=0;

void serialComm(){
    char c;
    float f;
    
    pc.printf("Average cycle time [us]: %f\n",cycT/cycN);
    cycT = 0;
    cycN = 0;
    
    if (pc.readable()) { 
        c = pc.getc();
        pc.scanf("%f", &f);
        switch (c) {
            case 'p':
                pGain = f;   
                pc.printf("Changed p gain to %f.\n",pGain);
                break;
            case 'i':
                iGain = f;   
                pc.printf("Changed i gain to %f.\n",iGain);
                break;
            default:
                pc.printf("Command not understood.\n",iGain);
                pc.printf("Read %c and %f.\n",c,f);
                break;
        }
    }
}

void limitIntegrator(){ 
    if (integrator > 3.3) {
            integrator = 3.3;
        }
    if (integrator < -3.3) {
        integrator = -3.3;
    }
}

int main() {
    float err=0.;
    int ctl=0;
    int pd=0; 
    pc.printf("mbed restarted!\n");
    
    adcSPI.format(16,3);
    adcSPI.frequency(2000000); //2MHz
    
    //commTick.attach(&serialComm,0.5); //check serial every half second  
    //intTick.attach(&limitIntegrator,0.001); //check integrator overrun every ms  
    
    t.start();
    

    while(1) {
        adcCS = 0;
        ctl = adcSPI.write(3<<13); //select ch 1
        adcCS = 1;
        wait_us(20);
        adcCS = 0;
        pd = adcSPI.write(1);       // select ch 0
        //take the last 12 bits that carry data
        // for some reason, it seems shifted up by one...
        pd = (pd>>1) & 0xFFF;
        ctl = (ctl>>1) & 0xFFF;
        pc.printf("Read %i from V0 and %i from V1.\n",ctl,pd);
        adcCS = 1;
        wait_ms(100);
       /* err = ctl.read() - pd.read();  
        cycT += t.read_us();
        cycN += 1.;
        integrator += err * iGain * t.read_us(); 
        t.reset(); //reset timer to get next integration time 
             
        vca = err * pGain + integrator;        //analog output
        
        */
    }
}