h

Dependencies:   mbed

main.cpp

Committer:
matthewhall115
Date:
2017-11-28
Revision:
0:0a16dac05e84

File content as of revision 0:0a16dac05e84:

#include "mbed.h"
// ES305 Lab #7

//program to drive the DC motor with a user specified duty cycle

// include libraries and define PI
#include "mbed.h"
#include "mbedWSEsbc.h"
#define PI (3.14159)

Ticker Controller;

//declare variables for data handling
float TotalTime; //establishing float called Totalime
float UserDutyCycle; //establishing float called UserDutyCycle
float Time; //establishing float called Time
float DataStream = 0.01; //establishing float called DataStream
float Ts = .0083; //establishing float called Ts
float speed;  //establishing float called speed
float enc1, ang, angp, dc, dspd, spderr, kp; //encoder, angle, previous angle, duty cycle
float K = 0.3996; //establishing float, gain, called K
float dc_p; //establishing float, dc_p, dc previous
float spderr_p ;//establishing float, spderr_p, desired speed previous


//declare function definitions
void ctrCode(); //function attaches to ticker
void pCtrlCode();
void piCtrlCode();


int main ()

{
    mbedWSEsbcInit(115200);
    mot_en1.period(0.020);

    while(1)    {
        pc.scanf("%f,%f,%f", &TotalTime,&dspd, &kp);

//Set current time to zero
        Time = 0.0;
        t.reset();

        //attach ctrCode function ticker to the obj with specified period

        Controller.attach(&piCtrlCode,Ts);
void piCtrlCode() // function to attach to ticker
{

    // Read encoder
    enc1 = LS7366_read_counter(1); // input is the encoder channel

    // Convert from counts to radians
    ang = 2.0*PI*enc1/6400.0;

    // Estimate speed
    speed = (ang-angp)/Ts;

    // compute error
    spderr = dspd-speed;
    
    // Age variables
    angp = ang;
    

    // compute duty cycle for motor
    if(Time<0.1) {
        dc = 0.0;
    } else {
        dc = (dc_p + K*(1.079*spderr - 0.9213*spderr_p)/20);
    }
    
    dc_p = dc;
    spderr_p = spderr;
    
    // enforce duty cycle saturation
    if(dc>1.0) {
        dc = 1.0;
    } else if(dc<-1.0) {
        dc = -1.0;
    }
    // motor control
    mot_control(1,dc); // first input is the motor channel, second is duty cycle
} //end pictrl function