blob: 0c191d132101a06f5e191c3f563851eb6591b7a9 [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).
246 static constexpr double rb = 0.9603 / 2.0;
247 static constexpr double kWheelRadius = 0.0515938;
248 // Resistance of the motor, divided by the number of motors.
249 static constexpr double kR =
250 (12.0 / kStallCurrent / 2 + 0.03) / (0.93 * 0.93);
251 // 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
321 wheel_ = sin(angular_range * wheel) / sin(angular_range);
322 wheel_ = sin(angular_range * wheel_) / sin(angular_range);
323 wheel_ *= 2.3;
324 quickturn_ = quickturn;
325
326 static const double kThrottleDeadband = 0.05;
327 if (::std::abs(throttle) < kThrottleDeadband) {
328 throttle_ = 0;
329 } else {
330 throttle_ = copysign((::std::abs(throttle) - kThrottleDeadband) /
331 (1.0 - kThrottleDeadband),
332 throttle);
333 }
334
335 // TODO(austin): Fix the upshift logic to include states.
336 Gear requested_gear;
337 if (false) {
338 const double current_left_velocity =
339 (position_.left_encoder - last_position_.left_encoder) /
340 position_time_delta_;
341 const double current_right_velocity =
342 (position_.right_encoder - last_position_.right_encoder) /
343 position_time_delta_;
344
345 Gear left_requested = ComputeGear(kDrivetrainLeftShifter,
346 current_left_velocity, left_gear_);
347 Gear right_requested = ComputeGear(kDrivetrainRightShifter,
348 current_right_velocity, right_gear_);
349 requested_gear =
350 (left_requested == HIGH || right_requested == HIGH) ? HIGH : LOW;
351 } else {
352 requested_gear = highgear ? HIGH : LOW;
353 }
354
355 const Gear shift_up = kDrivetrainClutchTransmission ? HIGH : SHIFTING_UP;
356 const Gear shift_down = kDrivetrainClutchTransmission ? LOW : SHIFTING_DOWN;
357
358 if (left_gear_ != requested_gear) {
359 if (IsInGear(left_gear_)) {
360 if (requested_gear == HIGH) {
361 left_gear_ = shift_up;
362 } else {
363 left_gear_ = shift_down;
364 }
365 } else {
366 if (requested_gear == HIGH && left_gear_ == SHIFTING_DOWN) {
367 left_gear_ = SHIFTING_UP;
368 } else if (requested_gear == LOW && left_gear_ == SHIFTING_UP) {
369 left_gear_ = SHIFTING_DOWN;
370 }
371 }
372 }
373 if (right_gear_ != requested_gear) {
374 if (IsInGear(right_gear_)) {
375 if (requested_gear == HIGH) {
376 right_gear_ = shift_up;
377 } else {
378 right_gear_ = shift_down;
379 }
380 } else {
381 if (requested_gear == HIGH && right_gear_ == SHIFTING_DOWN) {
382 right_gear_ = SHIFTING_UP;
383 } else if (requested_gear == LOW && right_gear_ == SHIFTING_UP) {
384 right_gear_ = SHIFTING_DOWN;
385 }
386 }
387 }
388 }
389 void SetPosition(const DrivetrainQueue::Position *position) {
390 if (position == NULL) {
391 ++stale_count_;
392 } else {
393 last_position_ = position_;
394 position_ = *position;
395 position_time_delta_ = (stale_count_ + 1) * 0.01;
396 stale_count_ = 0;
397 }
398
399#if HAVE_SHIFTERS
400 if (position) {
401 GearLogging gear_logging;
402 // Switch to the correct controller.
403 const double left_middle_shifter_position =
404 (kDrivetrainLeftShifter.clear_high +
405 kDrivetrainLeftShifter.clear_low) /
406 2.0;
407 const double right_middle_shifter_position =
408 (kDrivetrainRightShifter.clear_high +
409 kDrivetrainRightShifter.clear_low) /
410 2.0;
411
412 if (position->left_shifter_position < left_middle_shifter_position ||
413 left_gear_ == LOW) {
414 if (position->right_shifter_position < right_middle_shifter_position ||
415 right_gear_ == LOW) {
416 gear_logging.left_loop_high = false;
417 gear_logging.right_loop_high = false;
418 loop_->set_controller_index(gear_logging.controller_index = 0);
419 } else {
420 gear_logging.left_loop_high = false;
421 gear_logging.right_loop_high = true;
422 loop_->set_controller_index(gear_logging.controller_index = 1);
423 }
424 } else {
425 if (position->right_shifter_position < right_middle_shifter_position ||
426 right_gear_ == LOW) {
427 gear_logging.left_loop_high = true;
428 gear_logging.right_loop_high = false;
429 loop_->set_controller_index(gear_logging.controller_index = 2);
430 } else {
431 gear_logging.left_loop_high = true;
432 gear_logging.right_loop_high = true;
433 loop_->set_controller_index(gear_logging.controller_index = 3);
434 }
435 }
436
437 // TODO(austin): Constants.
438 if (position->left_shifter_position > kDrivetrainLeftShifter.clear_high &&
439 left_gear_ == SHIFTING_UP) {
440 left_gear_ = HIGH;
441 }
442 if (position->left_shifter_position < kDrivetrainLeftShifter.clear_low &&
443 left_gear_ == SHIFTING_DOWN) {
444 left_gear_ = LOW;
445 }
446 if (position->right_shifter_position >
447 kDrivetrainRightShifter.clear_high &&
448 right_gear_ == SHIFTING_UP) {
449 right_gear_ = HIGH;
450 }
451 if (position->right_shifter_position <
452 kDrivetrainRightShifter.clear_low &&
453 right_gear_ == SHIFTING_DOWN) {
454 right_gear_ = LOW;
455 }
456
457 gear_logging.left_state = left_gear_;
458 gear_logging.right_state = right_gear_;
459 LOG_STRUCT(DEBUG, "state", gear_logging);
460 }
461#endif
462 }
463
464 double FilterVelocity(double throttle) {
465 const Eigen::Matrix<double, 2, 2> FF =
466 loop_->B().inverse() *
467 (Eigen::Matrix<double, 2, 2>::Identity() - loop_->A());
468
469 constexpr int kHighGearController = 3;
470 const Eigen::Matrix<double, 2, 2> FF_high =
471 loop_->controller(kHighGearController).plant.B().inverse() *
472 (Eigen::Matrix<double, 2, 2>::Identity() -
473 loop_->controller(kHighGearController).plant.A());
474
475 ::Eigen::Matrix<double, 1, 2> FF_sum = FF.colwise().sum();
476 int min_FF_sum_index;
477 const double min_FF_sum = FF_sum.minCoeff(&min_FF_sum_index);
478 const double min_K_sum = loop_->K().col(min_FF_sum_index).sum();
479 const double high_min_FF_sum = FF_high.col(0).sum();
480
481 const double adjusted_ff_voltage = ::aos::Clip(
482 throttle * 12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0);
483 return (adjusted_ff_voltage +
484 ttrust_ * min_K_sum * (loop_->X_hat(0, 0) + loop_->X_hat(1, 0)) /
485 2.0) /
486 (ttrust_ * min_K_sum + min_FF_sum);
487 }
488
489 double MaxVelocity() {
490 const Eigen::Matrix<double, 2, 2> FF =
491 loop_->B().inverse() *
492 (Eigen::Matrix<double, 2, 2>::Identity() - loop_->A());
493
494 constexpr int kHighGearController = 3;
495 const Eigen::Matrix<double, 2, 2> FF_high =
496 loop_->controller(kHighGearController).plant.B().inverse() *
497 (Eigen::Matrix<double, 2, 2>::Identity() -
498 loop_->controller(kHighGearController).plant.A());
499
500 ::Eigen::Matrix<double, 1, 2> FF_sum = FF.colwise().sum();
501 int min_FF_sum_index;
502 const double min_FF_sum = FF_sum.minCoeff(&min_FF_sum_index);
503 // const double min_K_sum = loop_->K().col(min_FF_sum_index).sum();
504 const double high_min_FF_sum = FF_high.col(0).sum();
505
506 const double adjusted_ff_voltage =
507 ::aos::Clip(12.0 * min_FF_sum / high_min_FF_sum, -12.0, 12.0);
508 return adjusted_ff_voltage / min_FF_sum;
509 }
510
511 void Update() {
512 // TODO(austin): Observer for the current velocity instead of difference
513 // calculations.
514 ++counter_;
515#if HAVE_SHIFTERS
516 const double current_left_velocity =
517 (position_.left_encoder - last_position_.left_encoder) /
518 position_time_delta_;
519 const double current_right_velocity =
520 (position_.right_encoder - last_position_.right_encoder) /
521 position_time_delta_;
522 const double left_motor_speed =
523 MotorSpeed(kDrivetrainLeftShifter, position_.left_shifter_position,
524 current_left_velocity);
525 const double right_motor_speed =
526 MotorSpeed(kDrivetrainRightShifter, position_.right_shifter_position,
527 current_right_velocity);
528
529 {
530 CIMLogging logging;
531
532 // Reset the CIM model to the current conditions to be ready for when we
533 // shift.
534 if (IsInGear(left_gear_)) {
535 logging.left_in_gear = true;
536 } else {
537 logging.left_in_gear = false;
538 }
539 logging.left_motor_speed = left_motor_speed;
540 logging.left_velocity = current_left_velocity;
541 if (IsInGear(right_gear_)) {
542 logging.right_in_gear = true;
543 } else {
544 logging.right_in_gear = false;
545 }
546 logging.right_motor_speed = right_motor_speed;
547 logging.right_velocity = current_right_velocity;
548
549 LOG_STRUCT(DEBUG, "currently", logging);
550 }
551#endif
552
553#if HAVE_SHIFTERS
554 if (IsInGear(left_gear_) && IsInGear(right_gear_)) {
555#else
556 {
557#endif
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 LOG(DEBUG, "l=%f r=%f\n", left_velocity, right_velocity);
581
582 // Integrate velocity to get the position.
583 // This position is used to get integral control.
584 loop_->mutable_R() << left_velocity, right_velocity;
585
586 if (!quickturn_) {
587 // K * R = w
588 Eigen::Matrix<double, 1, 2> equality_k;
589 equality_k << 1 + sign_svel, -(1 - sign_svel);
590 const double equality_w = 0.0;
591
592 // Construct a constraint on R by manipulating the constraint on U
593 ::aos::controls::HPolytope<2> R_poly = ::aos::controls::HPolytope<2>(
594 U_Poly_.H() * (loop_->K() + FF),
595 U_Poly_.k() + U_Poly_.H() * loop_->K() * loop_->X_hat());
596
597 // Limit R back inside the box.
598 loop_->mutable_R() = frc971::control_loops::CoerceGoal(
599 R_poly, equality_k, equality_w, loop_->R());
600 }
601
602 const Eigen::Matrix<double, 2, 1> FF_volts = FF * loop_->R();
603 const Eigen::Matrix<double, 2, 1> U_ideal =
604 loop_->K() * (loop_->R() - loop_->X_hat()) + FF_volts;
605
606 for (int i = 0; i < 2; i++) {
607 loop_->mutable_U()[i] = ::aos::Clip(U_ideal[i], -12, 12);
608 }
609
610 // TODO(austin): Model this better.
611 // TODO(austin): Feed back?
612 loop_->mutable_X_hat() =
613 loop_->A() * loop_->X_hat() + loop_->B() * loop_->U();
614#if HAVE_SHIFTERS
615 } else {
616 // Any motor is not in gear. Speed match.
617 ::Eigen::Matrix<double, 1, 1> R_left;
618 ::Eigen::Matrix<double, 1, 1> R_right;
619 R_left(0, 0) = left_motor_speed;
620 R_right(0, 0) = right_motor_speed;
621
622 const double wiggle =
623 (static_cast<double>((counter_ % 20) / 10) - 0.5) * 5.0;
624
625 loop_->mutable_U(0, 0) =
626 ::aos::Clip((R_left / Kv)(0, 0) + (IsInGear(left_gear_) ? 0 : wiggle),
627 -12.0, 12.0);
628 loop_->mutable_U(1, 0) = ::aos::Clip(
629 (R_right / Kv)(0, 0) + (IsInGear(right_gear_) ? 0 : wiggle), -12.0,
630 12.0);
631 loop_->mutable_U() *= 12.0 / ::aos::robot_state->voltage_battery;
632#endif
633 }
634 }
635
636 void SendMotors(DrivetrainQueue::Output *output) {
637 if (output != NULL) {
638 output->left_voltage = loop_->U(0, 0);
639 output->right_voltage = loop_->U(1, 0);
640 output->left_high = left_gear_ == HIGH || left_gear_ == SHIFTING_UP;
641 output->right_high = right_gear_ == HIGH || right_gear_ == SHIFTING_UP;
642 }
643 }
644
645 private:
646 const ::aos::controls::HPolytope<2> U_Poly_;
647
648 ::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_;
649
650 const double ttrust_;
651 double wheel_;
652 double throttle_;
653 bool quickturn_;
654 int stale_count_;
655 double position_time_delta_;
656 Gear left_gear_;
657 Gear right_gear_;
658 DrivetrainQueue::Position last_position_;
659 DrivetrainQueue::Position position_;
660 int counter_;
661};
662constexpr double PolyDrivetrain::kStallTorque;
663constexpr double PolyDrivetrain::kStallCurrent;
664constexpr double PolyDrivetrain::kFreeSpeed;
665constexpr double PolyDrivetrain::kFreeCurrent;
666constexpr double PolyDrivetrain::J;
667constexpr double PolyDrivetrain::m;
668constexpr double PolyDrivetrain::rb;
669constexpr double PolyDrivetrain::kWheelRadius;
670constexpr double PolyDrivetrain::kR;
671constexpr double PolyDrivetrain::Kv;
672constexpr double PolyDrivetrain::Kt;
673
674void DrivetrainLoop::RunIteration(const DrivetrainQueue::Goal *goal,
675 const DrivetrainQueue::Position *position,
676 DrivetrainQueue::Output *output,
677 DrivetrainQueue::Status *status) {
678 // TODO(aschuh): These should be members of the class.
679 static DrivetrainMotorsSS dt_closedloop;
680 static PolyDrivetrain dt_openloop;
681
682 bool bad_pos = false;
683 if (position == nullptr) {
684 LOG_INTERVAL(no_position_);
685 bad_pos = true;
686 }
687 no_position_.Print();
688
689 bool control_loop_driving = false;
690 if (goal) {
691 double wheel = goal->steering;
692 double throttle = goal->throttle;
693 bool quickturn = goal->quickturn;
694#if HAVE_SHIFTERS
695 bool highgear = goal->highgear;
696#endif
697
698 control_loop_driving = goal->control_loop_driving;
699 double left_goal = goal->left_goal;
700 double right_goal = goal->right_goal;
701
702 dt_closedloop.SetGoal(left_goal, goal->left_velocity_goal, right_goal,
703 goal->right_velocity_goal);
704#if HAVE_SHIFTERS
705 dt_openloop.SetGoal(wheel, throttle, quickturn, highgear);
706#else
707 dt_openloop.SetGoal(wheel, throttle, quickturn, false);
708#endif
709 }
710
711 if (!bad_pos) {
712 const double left_encoder = position->left_encoder;
713 const double right_encoder = position->right_encoder;
714 if (gyro_reading.FetchLatest()) {
715 LOG_STRUCT(DEBUG, "using", *gyro_reading.get());
716 dt_closedloop.SetPosition(left_encoder, right_encoder,
717 gyro_reading->angle);
718 } else {
719 dt_closedloop.SetRawPosition(left_encoder, right_encoder);
720 }
721 }
722 dt_openloop.SetPosition(position);
723 dt_openloop.Update();
724
725 if (control_loop_driving) {
726 dt_closedloop.Update(output == NULL, true);
727 dt_closedloop.SendMotors(output);
728 } else {
729 dt_openloop.SendMotors(output);
730 if (output) {
731 dt_closedloop.SetExternalMotors(output->left_voltage,
732 output->right_voltage);
733 }
734 dt_closedloop.Update(output == NULL, false);
735 }
736
737 // set the output status of the control loop state
738 if (status) {
739 bool done = false;
740 if (goal) {
741 done = ((::std::abs(goal->left_goal -
742 dt_closedloop.GetEstimatedLeftEncoder()) <
743 kDrivetrainDoneDistance) &&
744 (::std::abs(goal->right_goal -
745 dt_closedloop.GetEstimatedRightEncoder()) <
746 kDrivetrainDoneDistance));
747 }
748 status->is_done = done;
749 status->robot_speed = dt_closedloop.GetEstimatedRobotSpeed();
750 status->filtered_left_position = dt_closedloop.GetEstimatedLeftEncoder();
751 status->filtered_right_position = dt_closedloop.GetEstimatedRightEncoder();
752
753 status->filtered_left_velocity = dt_closedloop.loop().X_hat(1, 0);
754 status->filtered_right_velocity = dt_closedloop.loop().X_hat(3, 0);
755 status->output_was_capped = dt_closedloop.OutputWasCapped();
756 status->uncapped_left_voltage = dt_closedloop.loop().U_uncapped(0, 0);
757 status->uncapped_right_voltage = dt_closedloop.loop().U_uncapped(1, 0);
758 }
759}
760
761} // namespace control_loops
762} // namespace bot3