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