-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmotor_control.cpp
86 lines (79 loc) · 2.26 KB
/
motor_control.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "motor_control.h"
#include <wiringPi.h>
#include <softPwm.h>
#include <stdexcept>
#include <string>
// Define the PWM range for softPwm
static const int PWM_RANGE = 100;
void init_gpio() {
if (wiringPiSetupGpio() == -1) {
throw std::runtime_error("Failed to initialize GPIO using wiringPi.");
}
// Pin initialization is handled in the MotorDriver constructor.
}
void cleanup_gpio() {
// You may choose to set all used pins to LOW here if needed.
}
// MotorDriver implementation
MotorDriver::MotorDriver(int in1, int in2, int en)
: in1_pin(in1), in2_pin(in2), en_pin(en)
{
pinMode(in1_pin, OUTPUT);
pinMode(in2_pin, OUTPUT);
pinMode(en_pin, OUTPUT);
digitalWrite(in1_pin, LOW);
digitalWrite(in2_pin, LOW);
// Initialize software PWM on the enable pin.
softPwmCreate(en_pin, 0, PWM_RANGE);
}
void MotorDriver::set_speed(int speed) {
if (speed > 0) {
digitalWrite(in1_pin, HIGH);
digitalWrite(in2_pin, LOW);
softPwmWrite(en_pin, speed);
} else if (speed < 0) {
digitalWrite(in1_pin, LOW);
digitalWrite(in2_pin, HIGH);
softPwmWrite(en_pin, -speed);
} else {
digitalWrite(in1_pin, LOW);
digitalWrite(in2_pin, LOW);
softPwmWrite(en_pin, 0);
}
}
void MotorDriver::stop() {
set_speed(0);
}
void mecanum_drive(MotorDriver &lf, MotorDriver &lr, MotorDriver &rf, MotorDriver &rr, const std::string &command, int speed) {
if (command == "forward") {
lf.set_speed(speed);
lr.set_speed(speed);
rf.set_speed(speed);
rr.set_speed(speed);
} else if (command == "backward") {
lf.set_speed(-speed);
lr.set_speed(-speed);
rf.set_speed(-speed);
rr.set_speed(-speed);
} else if (command == "rotate_left") {
lf.set_speed(-speed);
lr.set_speed(-speed);
rf.set_speed(speed);
rr.set_speed(speed);
} else if (command == "rotate_right") {
lf.set_speed(speed);
lr.set_speed(speed);
rf.set_speed(-speed);
rr.set_speed(-speed);
} else if (command == "stop") {
lf.stop();
lr.stop();
rf.stop();
rr.stop();
} else {
lf.stop();
lr.stop();
rf.stop();
rr.stop();
}
}