blob: bf8151009f1f0e6edae1b5367d53886f78c09fc7 [file] [log] [blame]
Daniel Pettiaece37f2014-10-25 17:13:44 -07001#include "bot3/control_loops/drivetrain/drivetrain.h"
2
3#include <math.h>
4#include <stdio.h>
5#include <sched.h>
6
7#include <functional>
8#include <memory>
9
10#include "Eigen/Dense"
11
12#include "aos/common/logging/logging.h"
13#include "aos/common/controls/polytope.h"
14#include "aos/common/commonmath.h"
15#include "aos/common/logging/queue_logging.h"
16#include "aos/common/logging/matrix_logging.h"
17
18#include "bot3/control_loops/drivetrain/drivetrain.q.h"
19#include "bot3/control_loops/drivetrain/drivetrain_constants.h"
20#include "bot3/control_loops/drivetrain/drivetrain_dog_motor_plant.h"
21#include "bot3/control_loops/drivetrain/polydrivetrain_cim_plant.h"
22#include "bot3/control_loops/drivetrain/polydrivetrain_dog_motor_plant.h"
Daniel Petti532c3e92014-11-04 22:15:19 -080023#include "bot3/shifter_hall_effect.h"
Daniel Pettiaece37f2014-10-25 17:13:44 -070024#include "frc971/control_loops/coerce_goal.h"
25#include "frc971/control_loops/state_feedback_loop.h"
26#include "frc971/queues/other_sensors.q.h"
27
28using ::frc971::sensors::gyro_reading;
29using ::frc971::control_loops::DoCoerceGoal;
30using ::frc971::control_loops::CoerceGoal;
31
32namespace bot3 {
33namespace control_loops {
34
35class DrivetrainMotorsSS {
36 public:
37 class LimitedDrivetrainLoop : public StateFeedbackLoop<4, 2, 2> {
38 public:
39 LimitedDrivetrainLoop(StateFeedbackLoop<4, 2, 2> &&loop)
40 : StateFeedbackLoop<4, 2, 2>(::std::move(loop)),
41 U_Poly_((Eigen::Matrix<double, 4, 2>() << 1, 0,
42 -1, 0,
43 0, 1,
44 0, -1).finished(),
45 (Eigen::Matrix<double, 4, 1>() << 12.0, 12.0,
46 12.0, 12.0).finished()) {
47 ::aos::controls::HPolytope<0>::Init();
48 T << 1, -1, 1, 1;
49 T_inverse = T.inverse();
50 }
51
52 bool output_was_capped() const {
53 return output_was_capped_;
54 }
55
56 private:
57 virtual void CapU() {
58 const Eigen::Matrix<double, 4, 1> error = R() - X_hat();
59
60 if (::std::abs(U(0, 0)) > 12.0 || ::std::abs(U(1, 0)) > 12.0) {
61 output_was_capped_ = true;
62 LOG_MATRIX(DEBUG, "U at start", U());
63
64 Eigen::Matrix<double, 2, 2> position_K;
65 position_K << K(0, 0), K(0, 2),
66 K(1, 0), K(1, 2);
67 Eigen::Matrix<double, 2, 2> velocity_K;
68 velocity_K << K(0, 1), K(0, 3),
69 K(1, 1), K(1, 3);
70
71 Eigen::Matrix<double, 2, 1> position_error;
72 position_error << error(0, 0), error(2, 0);
73 const auto drive_error = T_inverse * position_error;
74 Eigen::Matrix<double, 2, 1> velocity_error;
75 velocity_error << error(1, 0), error(3, 0);
76 LOG_MATRIX(DEBUG, "error", error);
77
78 const auto &poly = U_Poly_;
79 const Eigen::Matrix<double, 4, 2> pos_poly_H =
80 poly.H() * position_K * T;
81 const Eigen::Matrix<double, 4, 1> pos_poly_k =
82 poly.k() - poly.H() * velocity_K * velocity_error;
83 const ::aos::controls::HPolytope<2> pos_poly(pos_poly_H, pos_poly_k);
84
85 Eigen::Matrix<double, 2, 1> adjusted_pos_error;
86 {
87 const auto &P = drive_error;
88
89 Eigen::Matrix<double, 1, 2> L45;
90 L45 << ::aos::sign(P(1, 0)), -::aos::sign(P(0, 0));
91 const double w45 = 0;
92
93 Eigen::Matrix<double, 1, 2> LH;
94 if (::std::abs(P(0, 0)) > ::std::abs(P(1, 0))) {
95 LH << 0, 1;
96 } else {
97 LH << 1, 0;
98 }
99 const double wh = LH.dot(P);
100
101 Eigen::Matrix<double, 2, 2> standard;
102 standard << L45, LH;
103 Eigen::Matrix<double, 2, 1> W;
104 W << w45, wh;
105 const Eigen::Matrix<double, 2, 1> intersection =
106 standard.inverse() * W;
107
108 bool is_inside_h;
109 const auto adjusted_pos_error_h =
110 DoCoerceGoal(pos_poly, LH, wh, drive_error, &is_inside_h);
111 const auto adjusted_pos_error_45 =
112 DoCoerceGoal(pos_poly, L45, w45, intersection, nullptr);
113 if (pos_poly.IsInside(intersection)) {
114 adjusted_pos_error = adjusted_pos_error_h;
115 } else {
116 if (is_inside_h) {
117 if (adjusted_pos_error_h.norm() > adjusted_pos_error_45.norm()) {
118 adjusted_pos_error = adjusted_pos_error_h;
119 } else {
120 adjusted_pos_error = adjusted_pos_error_45;
121 }
122 } else {
123 adjusted_pos_error = adjusted_pos_error_45;
124 }
125 }
126 }
127
128 LOG_MATRIX(DEBUG, "adjusted_pos_error", adjusted_pos_error);
129 mutable_U() =
130 velocity_K * velocity_error + position_K * T * adjusted_pos_error;
131 LOG_MATRIX(DEBUG, "U is now", U());
132 } else {
133 output_was_capped_ = false;
134 }
135 }
136
137 const ::aos::controls::HPolytope<2> U_Poly_;
138 Eigen::Matrix<double, 2, 2> T, T_inverse;
139 bool output_was_capped_ = false;;
140 };
141
142 DrivetrainMotorsSS()
143 : loop_(new LimitedDrivetrainLoop(
144 MakeDrivetrainLoop())),
145 filtered_offset_(0.0),
146 gyro_(0.0),
147 left_goal_(0.0),
148 right_goal_(0.0),
149 raw_left_(0.0),
150 raw_right_(0.0) {
151 // Low gear on both.
152 loop_->set_controller_index(0);
153 }
154
155 void SetGoal(double left, double left_velocity, double right,
156 double right_velocity) {
157 left_goal_ = left;
158 right_goal_ = right;
159 loop_->mutable_R() << left, left_velocity, right, right_velocity;
160 }
161 void SetRawPosition(double left, double right) {
162 raw_right_ = right;
163 raw_left_ = left;
164 Eigen::Matrix<double, 2, 1> Y;
165 Y << left + filtered_offset_, right - filtered_offset_;
166 loop_->Correct(Y);
167 }
168 void SetPosition(double left, double right, double gyro) {
169 // Decay the offset quickly because this gyro is great.
170 const double offset =
171 (right - left - gyro * kBot3TurnWidth) / 2.0;
172 // TODO(brians): filtered_offset_ = offset first time around.
173 filtered_offset_ = 0.25 * offset + 0.75 * filtered_offset_;
174 gyro_ = gyro;
175 SetRawPosition(left, right);
176 }
177
178 void SetExternalMotors(double left_voltage, double right_voltage) {
179 loop_->mutable_U() << left_voltage, right_voltage;
180 }
181
182 void Update(bool stop_motors, bool enable_control_loop) {
183 if (enable_control_loop) {
184 loop_->Update(stop_motors);
185 } else {
186 if (stop_motors) {
187 loop_->mutable_U().setZero();
188 loop_->mutable_U_uncapped().setZero();
189 }
190 loop_->UpdateObserver();
191 }
192 ::Eigen::Matrix<double, 4, 1> E = loop_->R() - loop_->X_hat();
193 LOG_MATRIX(DEBUG, "E", E);
194 }
195
196 double GetEstimatedRobotSpeed() const {
197 // lets just call the average of left and right velocities close enough
198 return (loop_->X_hat(1, 0) + loop_->X_hat(3, 0)) / 2;
199 }
200
201 double GetEstimatedLeftEncoder() const {
202 return loop_->X_hat(0, 0);
203 }
204
205 double GetEstimatedRightEncoder() const {
206 return loop_->X_hat(2, 0);
207 }
208
209 bool OutputWasCapped() const {
210 return loop_->output_was_capped();
211 }
212
213 void SendMotors(Drivetrain::Output *output) const {
214 if (output) {
215 output->left_voltage = loop_->U(0, 0);
216 output->right_voltage = loop_->U(1, 0);
217 output->left_high = false;
218 output->right_high = false;
219 }
220 }
221
222 const LimitedDrivetrainLoop &loop() const { return *loop_; }
223
224 private:
225 ::std::unique_ptr<LimitedDrivetrainLoop> loop_;
226
227 double filtered_offset_;
228 double gyro_;
229 double left_goal_;
230 double right_goal_;
231 double raw_left_;
232 double raw_right_;
233};
234
235class PolyDrivetrain {
236 public:
237
238 enum Gear {
239 HIGH,
240 LOW,
241 SHIFTING_UP,
242 SHIFTING_DOWN
243 };
244 // Stall Torque in N m
245 static constexpr double kStallTorque = 2.42;
246 // Stall Current in Amps
247 static constexpr double kStallCurrent = 133;
248 // Free Speed in RPM. Used number from last year.
249 static constexpr double kFreeSpeed = 4650.0;
250 // Free Current in Amps
251 static constexpr double kFreeCurrent = 2.7;
252 // Moment of inertia of the drivetrain in kg m^2
253 // Just borrowed from last year.
254 static constexpr double J = 6.4;
255 // Mass of the robot, in kg.
256 static constexpr double m = 68;
257 // Radius of the robot, in meters (from last year).
258 static constexpr double rb = 0.617998644 / 2.0;
259 static constexpr double kWheelRadius = 0.04445;
260 // Resistance of the motor, divided by the number of motors.
261 static constexpr double kR = (12.0 / kStallCurrent / 4 + 0.03) / (0.93 * 0.93);
262 // Motor velocity constant
263 static constexpr double Kv =
264 ((kFreeSpeed / 60.0 * 2.0 * M_PI) / (12.0 - kR * kFreeCurrent));
265 // Torque constant
266 static constexpr double Kt = kStallTorque / kStallCurrent;
267
268 PolyDrivetrain()
269 : U_Poly_((Eigen::Matrix<double, 4, 2>() << /*[[*/ 1, 0 /*]*/,
270 /*[*/ -1, 0 /*]*/,
271 /*[*/ 0, 1 /*]*/,
272 /*[*/ 0, -1 /*]]*/).finished(),
273 (Eigen::Matrix<double, 4, 1>() << /*[[*/ 12 /*]*/,
274 /*[*/ 12 /*]*/,
275 /*[*/ 12 /*]*/,
276 /*[*/ 12 /*]]*/).finished()),
277 loop_(new StateFeedbackLoop<2, 2, 2>(
278 MakeVelocityDrivetrainLoop())),
279 ttrust_(1.1),
280 wheel_(0.0),
281 throttle_(0.0),
282 quickturn_(false),
283 stale_count_(0),
284 position_time_delta_(0.01),
285 left_gear_(LOW),
286 right_gear_(LOW),
287 counter_(0) {
288
289 last_position_.Zero();
290 position_.Zero();
291 }
292 static bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; }
293
Daniel Petti532c3e92014-11-04 22:15:19 -0800294 static double MotorSpeed(const constants::ShifterHallEffect &hall_effect,
Daniel Pettiaece37f2014-10-25 17:13:44 -0700295 double shifter_position, double velocity) {
296 // TODO(austin): G_high, G_low and kWheelRadius
297 const double avg_hall_effect =
298 (hall_effect.clear_high + hall_effect.clear_low) / 2.0;
299
300 if (shifter_position > avg_hall_effect) {
301 return velocity / kBot3HighGearRatio / kWheelRadius;
302 } else {
303 return velocity / kBot3LowGearRatio / kWheelRadius;
304 }
305 }
306
Daniel Petti532c3e92014-11-04 22:15:19 -0800307 Gear ComputeGear(const constants::ShifterHallEffect &hall_effect,
Daniel Pettiaece37f2014-10-25 17:13:44 -0700308 double velocity, Gear current) {
309 const double low_omega = MotorSpeed(hall_effect, 0.0, ::std::abs(velocity));
310 const double high_omega =
311 MotorSpeed(hall_effect, 1.0, ::std::abs(velocity));
312
313 double high_torque = ((12.0 - high_omega / Kv) * Kt / kR);
314 double low_torque = ((12.0 - low_omega / Kv) * Kt / kR);
315 double high_power = high_torque * high_omega;
316 double low_power = low_torque * low_omega;
317
318 // TODO(aschuh): Do this right!
319 if ((current == HIGH || high_power > low_power + 160) &&
320 ::std::abs(velocity) > 0.14) {
321 return HIGH;
322 } else {
323 return LOW;
324 }
325 }
326
327 void SetGoal(double wheel, double throttle, bool quickturn, bool highgear) {
328 const double kWheelNonLinearity = 0.3;
329 // Apply a sin function that's scaled to make it feel better.
330 const double angular_range = M_PI_2 * kWheelNonLinearity;
331 wheel_ = sin(angular_range * wheel) / sin(angular_range);
332 wheel_ = sin(angular_range * wheel_) / sin(angular_range);
333 quickturn_ = quickturn;
334
335 static const double kThrottleDeadband = 0.05;
336 if (::std::abs(throttle) < kThrottleDeadband) {
337 throttle_ = 0;
338 } else {
339 throttle_ = copysign((::std::abs(throttle) - kThrottleDeadband) /
340 (1.0 - kThrottleDeadband), throttle);
341 }
342
343 // TODO(austin): Fix the upshift logic to include states.
344 Gear requested_gear;
345 if (false) {
346 const double current_left_velocity =
347 (position_.left_encoder - last_position_.left_encoder) /
348 position_time_delta_;
349 const double current_right_velocity =
350 (position_.right_encoder - last_position_.right_encoder) /
351 position_time_delta_;
352
353 Gear left_requested =
354 ComputeGear(kBot3LeftDriveShifter, current_left_velocity, left_gear_);
355 Gear right_requested =
356 ComputeGear(kBot3RightDriveShifter, current_right_velocity, right_gear_);
357 requested_gear =
358 (left_requested == HIGH || right_requested == HIGH) ? HIGH : LOW;
359 } else {
360 requested_gear = highgear ? HIGH : LOW;
361 }
362
363 const Gear shift_up = SHIFTING_UP;
364 const Gear shift_down = SHIFTING_DOWN;
365
366 if (left_gear_ != requested_gear) {
367 if (IsInGear(left_gear_)) {
368 if (requested_gear == HIGH) {
369 left_gear_ = shift_up;
370 } else {
371 left_gear_ = shift_down;
372 }
373 } else {
374 if (requested_gear == HIGH && left_gear_ == SHIFTING_DOWN) {
375 left_gear_ = SHIFTING_UP;
376 } else if (requested_gear == LOW && left_gear_ == SHIFTING_UP) {
377 left_gear_ = SHIFTING_DOWN;
378 }
379 }
380 }
381 if (right_gear_ != requested_gear) {
382 if (IsInGear(right_gear_)) {
383 if (requested_gear == HIGH) {
384 right_gear_ = shift_up;
385 } else {
386 right_gear_ = shift_down;
387 }
388 } else {
389 if (requested_gear == HIGH && right_gear_ == SHIFTING_DOWN) {
390 right_gear_ = SHIFTING_UP;
391 } else if (requested_gear == LOW && right_gear_ == SHIFTING_UP) {
392 right_gear_ = SHIFTING_DOWN;
393 }
394 }
395 }
396 }
397 void SetPosition(const Drivetrain::Position *position) {
398 if (position == NULL) {
399 ++stale_count_;
400 } else {
401 last_position_ = position_;
402 position_ = *position;
403 position_time_delta_ = (stale_count_ + 1) * 0.01;
404 stale_count_ = 0;
405 }
406
407 if (position) {
408 GearLogging gear_logging;
409 // Switch to the correct controller.
410 const double left_middle_shifter_position =
411 (kBot3LeftDriveShifter.clear_high +
412 kBot3LeftDriveShifter.clear_low) / 2.0;
413 const double right_middle_shifter_position =
414 (kBot3RightDriveShifter.clear_high +
415 kBot3RightDriveShifter.clear_low) / 2.0;
416
417 if (position->left_shifter_position < left_middle_shifter_position) {
418 if (position->right_shifter_position < right_middle_shifter_position ||
419 right_gear_ == LOW) {
420 gear_logging.left_loop_high = false;
421 gear_logging.right_loop_high = false;
422 loop_->set_controller_index(gear_logging.controller_index = 0);
423 } else {
424 gear_logging.left_loop_high = false;
425 gear_logging.right_loop_high = true;
426 loop_->set_controller_index(gear_logging.controller_index = 1);
427 }
428 } else {
429 if (position->right_shifter_position < right_middle_shifter_position ||
430 left_gear_ == LOW) {
431 gear_logging.left_loop_high = true;
432 gear_logging.right_loop_high = false;
433 loop_->set_controller_index(gear_logging.controller_index = 2);
434 } else {
435 gear_logging.left_loop_high = true;
436 gear_logging.right_loop_high = true;
437 loop_->set_controller_index(gear_logging.controller_index = 3);
438 }
439 }
440
441 // TODO(austin): Constants.
442 if (position->left_shifter_position >
443 kBot3LeftDriveShifter.clear_high &&
444 left_gear_ == SHIFTING_UP) {
445 left_gear_ = HIGH;
446 }
447 if (position->left_shifter_position <
448 kBot3LeftDriveShifter.clear_low &&
449 left_gear_ == SHIFTING_DOWN) {
450 left_gear_ = LOW;
451 }
452 if (position->right_shifter_position >
453 kBot3RightDriveShifter.clear_high &&
454 right_gear_ == SHIFTING_UP) {
455 right_gear_ = HIGH;
456 }
457 if (position->right_shifter_position <
458 kBot3RightDriveShifter.clear_low &&
459 right_gear_ == SHIFTING_DOWN) {
460 right_gear_ = LOW;
461 }
462
463 gear_logging.left_state = left_gear_;
464 gear_logging.right_state = right_gear_;
465 LOG_STRUCT(DEBUG, "state", gear_logging);
466 }
467 }
468
469 double FilterVelocity(double throttle) {
470 const Eigen::Matrix<double, 2, 2> FF =
471 loop_->B().inverse() *
472 (Eigen::Matrix<double, 2, 2>::Identity() - loop_->A());
473
474 constexpr int kHighGearController = 3;
475 const Eigen::Matrix<double, 2, 2> FF_high =
476 loop_->controller(kHighGearController).plant.B().inverse() *
477 (Eigen::Matrix<double, 2, 2>::Identity() -
478 loop_->controller(kHighGearController).plant.A());
479
480 ::Eigen::Matrix<double, 1, 2> FF_sum = FF.colwise().sum();
481 int min_FF_sum_index;
482 const double min_FF_sum = FF_sum.minCoeff(&min_FF_sum_index);
483 const double min_K_sum = loop_->K().col(min_FF_sum_index).sum();
484 const double high_min_FF_sum = FF_high.col(0).sum();
485
486 const double adjusted_ff_voltage = ::aos::Clip(
487 throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0);
488 return ((adjusted_ff_voltage +
489 ttrust_ * min_K_sum * (loop_->X_hat(0, 0) + loop_->X_hat(1, 0)) / 2.0) /
490 (ttrust_ * min_K_sum + min_FF_sum));
491 }
492
493 double MaxVelocity() {
494 const Eigen::Matrix<double, 2, 2> FF =
495 loop_->B().inverse() *
496 (Eigen::Matrix<double, 2, 2>::Identity() - loop_->A());
497
498 constexpr int kHighGearController = 3;
499 const Eigen::Matrix<double, 2, 2> FF_high =
500 loop_->controller(kHighGearController).plant.B().inverse() *
501 (Eigen::Matrix<double, 2, 2>::Identity() -
502 loop_->controller(kHighGearController).plant.A());
503
504 ::Eigen::Matrix<double, 1, 2> FF_sum = FF.colwise().sum();
505 int min_FF_sum_index;
506 const double min_FF_sum = FF_sum.minCoeff(&min_FF_sum_index);
507 //const double min_K_sum = loop_->K().col(min_FF_sum_index).sum();
508 const double high_min_FF_sum = FF_high.col(0).sum();
509
510 const double adjusted_ff_voltage = ::aos::Clip(
511 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0);
512 return adjusted_ff_voltage / min_FF_sum;
513 }
514
515 void Update() {
516 // TODO(austin): Observer for the current velocity instead of difference
517 // calculations.
518 ++counter_;
519 const double current_left_velocity =
520 (position_.left_encoder - last_position_.left_encoder) /
521 position_time_delta_;
522 const double current_right_velocity =
523 (position_.right_encoder - last_position_.right_encoder) /
524 position_time_delta_;
525 const double left_motor_speed =
526 MotorSpeed(kBot3LeftDriveShifter,
527 position_.left_shifter_position,
528 current_left_velocity);
529 const double right_motor_speed =
530 MotorSpeed(kBot3RightDriveShifter,
531 position_.right_shifter_position,
532 current_right_velocity);
533
534 {
535 CIMLogging logging;
536
537 // Reset the CIM model to the current conditions to be ready for when we
538 // shift.
539 if (IsInGear(left_gear_)) {
540 logging.left_in_gear = true;
541 } else {
542 logging.left_in_gear = false;
543 }
544 logging.left_motor_speed = left_motor_speed;
545 logging.left_velocity = current_left_velocity;
546 if (IsInGear(right_gear_)) {
547 logging.right_in_gear = true;
548 } else {
549 logging.right_in_gear = false;
550 }
551 logging.right_motor_speed = right_motor_speed;
552 logging.right_velocity = current_right_velocity;
553
554 LOG_STRUCT(DEBUG, "currently", logging);
555 }
556
557 if (IsInGear(left_gear_) && IsInGear(right_gear_)) {
558 // FF * X = U (steady state)
559 const Eigen::Matrix<double, 2, 2> FF =
560 loop_->B().inverse() *
561 (Eigen::Matrix<double, 2, 2>::Identity() - loop_->A());
562
563 // Invert the plant to figure out how the velocity filter would have to
564 // work
565 // out in order to filter out the forwards negative inertia.
566 // This math assumes that the left and right power and velocity are
567 // equals,
568 // and that the plant is the same on the left and right.
569 const double fvel = FilterVelocity(throttle_);
570
571 const double sign_svel = wheel_ * ((fvel > 0.0) ? 1.0 : -1.0);
572 double steering_velocity;
573 if (quickturn_) {
574 steering_velocity = wheel_ * MaxVelocity();
575 } else {
576 steering_velocity = ::std::abs(fvel) * wheel_;
577 }
578 const double left_velocity = fvel - steering_velocity;
579 const double right_velocity = fvel + steering_velocity;
580
581 // Integrate velocity to get the position.
582 // This position is used to get integral control.
583 loop_->mutable_R() << left_velocity, right_velocity;
584
585 if (!quickturn_) {
586 // K * R = w
587 Eigen::Matrix<double, 1, 2> equality_k;
588 equality_k << 1 + sign_svel, -(1 - sign_svel);
589 const double equality_w = 0.0;
590
591 // Construct a constraint on R by manipulating the constraint on U
592 ::aos::controls::HPolytope<2> R_poly = ::aos::controls::HPolytope<2>(
593 U_Poly_.H() * (loop_->K() + FF),
594 U_Poly_.k() + U_Poly_.H() * loop_->K() * loop_->X_hat());
595
596 // Limit R back inside the box.
597 loop_->mutable_R() =
598 CoerceGoal(R_poly, equality_k, equality_w, loop_->R());
599 }
600
601 const Eigen::Matrix<double, 2, 1> FF_volts = FF * loop_->R();
602 const Eigen::Matrix<double, 2, 1> U_ideal =
603 loop_->K() * (loop_->R() - loop_->X_hat()) + FF_volts;
604
605 for (int i = 0; i < 2; i++) {
606 loop_->mutable_U()[i] = ::aos::Clip(U_ideal[i], -12, 12);
607 }
608
609 // TODO(austin): Model this better.
610 // TODO(austin): Feed back?
611 loop_->mutable_X_hat() =
612 loop_->A() * loop_->X_hat() + loop_->B() * loop_->U();
613 } else {
614 // Any motor is not in gear. Speed match.
615 ::Eigen::Matrix<double, 1, 1> R_left;
616 ::Eigen::Matrix<double, 1, 1> R_right;
617 R_left(0, 0) = left_motor_speed;
618 R_right(0, 0) = right_motor_speed;
619
620 const double wiggle =
621 (static_cast<double>((counter_ % 20) / 10) - 0.5) * 5.0;
622
623 loop_->mutable_U(0, 0) = ::aos::Clip(
624 (R_left / Kv)(0, 0) + (IsInGear(left_gear_) ? 0 : wiggle),
625 -12.0, 12.0);
626 loop_->mutable_U(1, 0) = ::aos::Clip(
627 (R_right / Kv)(0, 0) + (IsInGear(right_gear_) ? 0 : wiggle),
628 -12.0, 12.0);
629 loop_->mutable_U() *= 12.0 / position_.battery_voltage;
630 }
631 }
632
633 void SendMotors(Drivetrain::Output *output) {
634 if (output != NULL) {
635 output->left_voltage = loop_->U(0, 0);
636 output->right_voltage = loop_->U(1, 0);
637 output->left_high = left_gear_ == HIGH || left_gear_ == SHIFTING_UP;
638 output->right_high = right_gear_ == HIGH || right_gear_ == SHIFTING_UP;
639 }
640 }
641
642 private:
643 const ::aos::controls::HPolytope<2> U_Poly_;
644
645 ::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_;
646
647 const double ttrust_;
648 double wheel_;
649 double throttle_;
650 bool quickturn_;
651 int stale_count_;
652 double position_time_delta_;
653 Gear left_gear_;
654 Gear right_gear_;
655 Drivetrain::Position last_position_;
656 Drivetrain::Position position_;
657 int counter_;
658};
659constexpr double PolyDrivetrain::kStallTorque;
660constexpr double PolyDrivetrain::kStallCurrent;
661constexpr double PolyDrivetrain::kFreeSpeed;
662constexpr double PolyDrivetrain::kFreeCurrent;
663constexpr double PolyDrivetrain::J;
664constexpr double PolyDrivetrain::m;
665constexpr double PolyDrivetrain::rb;
666constexpr double PolyDrivetrain::kWheelRadius;
667constexpr double PolyDrivetrain::kR;
668constexpr double PolyDrivetrain::Kv;
669constexpr double PolyDrivetrain::Kt;
670
671
672void DrivetrainLoop::RunIteration(const Drivetrain::Goal *goal,
673 const Drivetrain::Position *position,
674 Drivetrain::Output *output,
675 Drivetrain::Status * status) {
676 // TODO(aschuh): These should be members of the class.
677 static DrivetrainMotorsSS dt_closedloop;
678 static PolyDrivetrain dt_openloop;
679
680 bool bad_pos = false;
681 if (position == nullptr) {
682 LOG_INTERVAL(no_position_);
683 bad_pos = true;
684 }
685 no_position_.Print();
686
687 double wheel = goal->steering;
688 double throttle = goal->throttle;
689 bool quickturn = goal->quickturn;
690 bool highgear = goal->highgear;
691
692 bool control_loop_driving = goal->control_loop_driving;
693 double left_goal = goal->left_goal;
694 double right_goal = goal->right_goal;
695
696 dt_closedloop.SetGoal(left_goal, goal->left_velocity_goal, right_goal,
697 goal->right_velocity_goal);
698 if (!bad_pos) {
699 const double left_encoder = position->left_encoder;
700 const double right_encoder = position->right_encoder;
701 if (gyro_reading.FetchLatest()) {
702 LOG_STRUCT(DEBUG, "using", *gyro_reading.get());
703 dt_closedloop.SetPosition(left_encoder, right_encoder,
704 gyro_reading->angle);
705 } else {
706 dt_closedloop.SetRawPosition(left_encoder, right_encoder);
707 }
708 }
709 dt_openloop.SetPosition(position);
710 dt_openloop.SetGoal(wheel, throttle, quickturn, highgear);
711 dt_openloop.Update();
712
713 if (control_loop_driving) {
714 dt_closedloop.Update(output == NULL, true);
715 dt_closedloop.SendMotors(output);
716 } else {
717 dt_openloop.SendMotors(output);
718 if (output) {
719 dt_closedloop.SetExternalMotors(output->left_voltage,
720 output->right_voltage);
721 }
722 dt_closedloop.Update(output == NULL, false);
723 }
724
725 // set the output status of the control loop state
726 if (status) {
727 bool done = false;
728 if (goal) {
729 done = ((::std::abs(goal->left_goal -
730 dt_closedloop.GetEstimatedLeftEncoder()) <
731 kBot3DrivetrainDoneDistance) &&
732 (::std::abs(goal->right_goal -
733 dt_closedloop.GetEstimatedRightEncoder()) <
734 kBot3DrivetrainDoneDistance));
735 }
736 status->is_done = done;
737 status->robot_speed = dt_closedloop.GetEstimatedRobotSpeed();
738 status->filtered_left_position = dt_closedloop.GetEstimatedLeftEncoder();
739 status->filtered_right_position = dt_closedloop.GetEstimatedRightEncoder();
740 status->output_was_capped = dt_closedloop.OutputWasCapped();
741 status->uncapped_left_voltage = dt_closedloop.loop().U_uncapped(0, 0);
742 status->uncapped_right_voltage = dt_closedloop.loop().U_uncapped(1, 0);
743 }
744}
745
746} // namespace control_loops
747} // namespace bot3