A class for driving a DC motor using a full-bridge (H-bridge) driver.

Dependencies:   RateLimiter

Dependents:   L298N-Breakout-Test Zavrsni_rad_NXP_cup

HBridgeDCMotor.cpp

Committer:
tbjazic
Date:
2015-01-14
Revision:
1:fb5553d9ff4c
Parent:
0:d3f1d0d52615
Child:
2:1675a4c00925

File content as of revision 1:fb5553d9ff4c:

#include "HBridgeDCMotor.h"

HBridgeDCMotor::HBridgeDCMotor(PinName gh_a, PinName gl_a, PinName gh_b, PinName gl_b) : GH_A(gh_a), GL_A(gl_a), GH_B(gh_b), GL_B(gl_b) {
    sampleTime = 1e-3;
    switchingPeriod = 1.0 / 20e3;
    dutyCycle = tempDutyCycle = 0;
    GH_A.period(switchingPeriod); // applies to all PwmOut instances
    rl.setLimits(0.1, -0.1, 0, sampleTime); // initial 10 second ramp
}

void HBridgeDCMotor::configure(float sampleTime, float switchingFrequency, float rampUpSlope, float rampDownSlope) {
    if (sampleTime < 1e-6)
        sampleTime = 1e-3;
    if (switchingFrequency < 100)
        switchingFrequency = 20e3;
    if (rampUpSlope < 0 || rampUpSlope > 1)
        rampUpSlope = 0.1;
    if (rampDownSlope > 0 || rampDownSlope < -1)
        rampDownSlope = -0.1;
    this->sampleTime = sampleTime;
    switchingPeriod = 1.0 / switchingFrequency;
    rl.setLimits(rampUpSlope, rampDownSlope, 0, sampleTime);
}

void HBridgeDCMotor::adjustDutyCycle() {
    dutyCycle = rl.out(tempDutyCycle);
    if (dutyCycle >= 0 && dutyCycle <= 1) {
        GH_B = 0;
        GL_B = 1;
        GL_A = 0;
        GH_A = dutyCycle;
    } else if (dutyCycle >= -1 && dutyCycle < 0) { // opposite direction
        GH_A = 0;
        GL_A = 1;
        GL_B = 0;
        GH_B = -dutyCycle;
    } else {
        coast();
    }
}

void HBridgeDCMotor::setDutyCycle(float dc) {
    if (dc >= -1 && dc <= 1) {
        ticker.attach(this, &HBridgeDCMotor::adjustDutyCycle, sampleTime);
        tempDutyCycle = dc;
    } else {
        coast();
    }
}

void HBridgeDCMotor::coast() {
    GH_A = 0;
    GL_A = 0;
    GH_B = 0;
    GL_B = 0;
    dutyCycle = tempDutyCycle = 0;
    rl.reset();
    ticker.detach();
}

float HBridgeDCMotor::getDutyCycle() {
    return dutyCycle;
}