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

Dependencies:   RateLimiter

Dependents:   L298N-Breakout-Test Zavrsni_rad_NXP_cup

Revision:
0:d3f1d0d52615
Child:
1:fb5553d9ff4c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HBridgeDCMotor.cpp	Wed Jan 14 08:51:14 2015 +0000
@@ -0,0 +1,49 @@
+#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::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;
+}
\ No newline at end of file