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