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