-
Notifications
You must be signed in to change notification settings - Fork 0
/
tb6612.cpp
157 lines (143 loc) · 2.62 KB
/
tb6612.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include "tb6612.h"
namespace tb6612
{
TB6612::TB6612(PinName pwm_a, PinName pwm_b, PinName a_in1, PinName a_in2, PinName b_in1, PinName b_in2,
MotorPolarity a_polarity, MotorPolarity b_polarity)
: pwm_a_(pwm_a), pwm_b_(pwm_b), a_in1_(a_in1), a_in2_(a_in2), b_in1_(b_in1), b_in2_(b_in2)
{
a_polarity_ = a_polarity;
b_polarity_ = b_polarity;
}
void TB6612::setPWMPeriod(float period_s)
{
pwm_a_.period(period_s);
pwm_b_.period(period_s);
}
Direction TB6612::handlePolarity(MotorPolarity polarity, Direction new_dir)
{
Direction ret_val;
if (STANDARD == polarity)
{
ret_val = new_dir;
}
else if (FORWARD == new_dir)
{
ret_val = REVERSE;
}
else if (REVERSE == new_dir)
{
ret_val = FORWARD;
}
else
{
MBED_ASSERT(false);
}
return ret_val;
}
void TB6612::setDirection(MotorId motor, Direction new_dir)
{
Direction dir;
if (MOTOR_A == motor)
{
dir = handlePolarity(a_polarity_, new_dir);
motor_a_dir_ = new_dir;
}
else if (MOTOR_B == motor)
{
dir = handlePolarity(b_polarity_, new_dir);
motor_b_dir_ = new_dir;
}
else
{
MBED_ASSERT(false);
}
switch (dir)
{
case FORWARD:
switch (motor)
{
case MOTOR_A:
a_in1_ = 1;
a_in2_ = 0;
break;
case MOTOR_B:
b_in1_ = 1;
b_in2_ = 0;
break;
default:
MBED_ASSERT(false);
}
break;
case REVERSE:
switch (motor)
{
case MOTOR_A:
a_in1_ = 0;
a_in2_ = 1;
break;
case MOTOR_B:
b_in1_ = 0;
b_in2_ = 1;
break;
default:
MBED_ASSERT(false);
}
break;
default:
MBED_ASSERT(false);
}
}
Direction TB6612::getDirection(MotorId motor)
{
Direction dir;
switch (motor)
{
case MOTOR_A:
dir = motor_a_dir_;
break;
case MOTOR_B:
dir = motor_b_dir_;
break;
default:
MBED_ASSERT(false);
}
return (dir);
}
void TB6612::setDutyCycle(MotorId motor, uint8_t percent)
{
switch (motor)
{
case MOTOR_A:
pwm_a_ = percent / 100.0f;
break;
case MOTOR_B:
pwm_b_ = percent / 100.0f;
break;
default:
MBED_ASSERT(false);
}
}
void TB6612::stop(MotorId motor)
{
switch (motor)
{
case MOTOR_A:
a_in1_ = 0;
a_in2_ = 0;
break;
case MOTOR_B:
b_in1_ = 0;
b_in2_ = 0;
break;
default:
MBED_ASSERT(false);
}
}
void TB6612::freewheel(void)
{
stop(MOTOR_A);
stop(MOTOR_B);
setDutyCycle(MOTOR_A, 100);
setDutyCycle(MOTOR_B, 100);
}
} // namespace tb6612