Biorobotica TIC / Mbed 2 deprecated Motoraansturing

Dependencies:   mbed

main.cpp

Committer:
Hubertus
Date:
2018-09-26
Revision:
0:e8e408160110

File content as of revision 0:e8e408160110:

#include "mbed.h"
#include "math.h"
//#include "HIDScope.h"

// ------ Hardware Interfaces -------

const PinName motor1dir = D7;
const PinName motor1PWM = D6;
//const PinName motor2PWM = D5;
//const PinName motor2dir = D4;

DigitalOut motor1direction(motor1dir);
PwmOut motor1control(motor1PWM);
//PwmOut motor2control(motor2PWM);
//DigitalOut motor2direction(motor2dir);

const PinName button1name = D1; 
const PinName pot1name = A1;
InterruptIn button1(button1name);
AnalogIn potMeterIn(pot1name);

// ------- Constants

const float motorGain = 6.3f;
const float maxVelocity = 6.3f; //radians per second
const bool clockwise = true;

// ------ variables

volatile bool direction = clockwise;


// ------- Objects used -------

// Ticker which controls the mother every 1/100 of a second.
Ticker controlTicker;

Ticker debugTicker;
Serial pc(USBTX, USBRX);

//------Functions

float getReferenceVelocity() {
    // Returns reference velocity in rad/s. 
    return maxVelocity * potMeterIn;
}

void setMotor1(float motorValue) {
    // Given motorValue<=1, writes the velocity to the pwm control.
    // MotorValues outside range are truncated to within range.
    motor1control.write(fabs(motorValue) > 1 ? 1 : fabs(motorValue));
}
float feedForwardControl(float referenceVelocity) {
    // very simple linear feed-forward control
    // returns motorValue
    return referenceVelocity / motorGain;
}

void measureAndControl(void) {
    // This function measures the potmeter position, extracts a
    // reference velocity from it, and controls the motor with 
    // a simple FeedForward controller. Call this from a Ticker.
    float referenceVelocity = getReferenceVelocity();
    float motorValue = feedForwardControl(referenceVelocity);
    setMotor1(motorValue);
}

void onButtonPress() {
    // reverses the direction
    motor1direction.write(direction = !direction);
     pc.printf("direction: %s\r\n\n", direction ? "clockwise" : "counter clockwise");
}

void onDebugTick() {
    
    pc.printf("pot input: %f\r\n", potMeterIn.read());
    pc.printf("motorValue: %f\r\n", feedForwardControl(getReferenceVelocity()));
    pc.printf("\n\n\n");
    
}


//----------- Main function
int main()
{
   pc.baud(115200);
    
    button1.fall(&onButtonPress);
    controlTicker.attach(&measureAndControl, 1.0/300.0);  //1f/100f is elke tijd dat hij deze functie weer aanroept
    debugTicker.attach(&onDebugTick, 1);    // elke seconde geeft hij waardes weer op pc

    while (true);
}