-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHBridgeMotor.cpp
More file actions
58 lines (45 loc) · 1.28 KB
/
HBridgeMotor.cpp
File metadata and controls
58 lines (45 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "HBridgeMotor.h"
#include "Arduino.h"
HBridgeMotor::HBridgeMotor(int motorType) {
this->hBConfig = hBConfigs[motorType];
}
void HBridgeMotor::setup(MotorConfig motorConfig) {
this->motorConfig = motorConfig;
pinMode(motorConfig.directionPin1, OUTPUT);
pinMode(motorConfig.enablePin, OUTPUT);
this->pwm = motorConfig.pwm;
if (hBConfig.pinMode == TWO_PIN)
pinMode(motorConfig.directionPin2, OUTPUT);
}
void HBridgeMotor::writeBits(short bits) {
digitalWrite(motorConfig.directionPin1, bits & 0x1);
if (hBConfig.pinMode == TWO_PIN)
digitalWrite(motorConfig.directionPin2, bits >> 1 & 0x1);
}
void HBridgeMotor::enable(bool on) {
int power = on ? pwm : 0;
analogWrite(motorConfig.enablePin, power);
}
void HBridgeMotor::forward() {
brake();
writeBits(hBConfig.bitsForward);
enable(true);
}
void HBridgeMotor::reverse() {
brake();
writeBits(hBConfig.bitsReverse);
enable(true);
}
void HBridgeMotor::brake() {
// Always set PWM to 0 when stopping
enable(false);
writeBits(hBConfig.bitsBrake);
}
void HBridgeMotor::stop() {
// Always set PWM to 0 when stopping
digitalWrite(motorConfig.enablePin, 0);
writeBits(hBConfig.bitsStop);
}
void HBridgeMotor::setPWM(int pwm) {
this->pwm = pwm;
}