blob: dd3a4b84c29a48fddc86c94e54d7cf7b6be3d03c [file] [log] [blame]
Brian Silverman6260c092018-01-14 15:21:36 -08001#include "motors/core/kinetis.h"
2
Brian Silverman6260c092018-01-14 15:21:36 -08003#include <inttypes.h>
Brian Silvermandabdf902017-10-21 15:34:40 -04004#include <stdio.h>
Brian Silverman6260c092018-01-14 15:21:36 -08005
6#include <atomic>
7#include <cmath>
8
Brian Silvermandabdf902017-10-21 15:34:40 -04009#include "frc971/control_loops/drivetrain/integral_haptic_trigger.h"
10#include "frc971/control_loops/drivetrain/integral_haptic_wheel.h"
Brian Silverman6260c092018-01-14 15:21:36 -080011#include "motors/core/time.h"
12#include "motors/motor.h"
13#include "motors/peripheral/adc.h"
14#include "motors/peripheral/can.h"
15#include "motors/pistol_grip/motor_controls.h"
16#include "motors/usb/cdc.h"
17#include "motors/usb/usb.h"
18#include "motors/util.h"
Brian Silverman6260c092018-01-14 15:21:36 -080019
20#define MOTOR0_PWM_FTM FTM3
21#define MOTOR0_ENCODER_FTM FTM2
22#define MOTOR1_PWM_FTM FTM0
23#define MOTOR1_ENCODER_FTM FTM1
24
25extern const float kWheelCoggingTorque[4096];
26extern const float kTriggerCoggingTorque[4096];
27
28namespace frc971 {
29namespace salsa {
30namespace {
31
32using ::frc971::control_loops::drivetrain::MakeIntegralHapticTriggerPlant;
33using ::frc971::control_loops::drivetrain::MakeIntegralHapticTriggerObserver;
34using ::frc971::control_loops::drivetrain::MakeIntegralHapticWheelPlant;
35using ::frc971::control_loops::drivetrain::MakeIntegralHapticWheelObserver;
36
37constexpr float kHapticWheelCurrentLimit = static_cast<float>(
38 ::frc971::control_loops::drivetrain::kHapticWheelCurrentLimit);
39constexpr float kHapticTriggerCurrentLimit = static_cast<float>(
40 ::frc971::control_loops::drivetrain::kHapticTriggerCurrentLimit);
41
42::std::atomic<Motor *> global_motor0{nullptr}, global_motor1{nullptr};
43::std::atomic<teensy::AcmTty *> global_stdout{nullptr};
44
45// Angle last time the current loop ran.
46::std::atomic<float> global_wheel_angle{0.0f};
47::std::atomic<float> global_trigger_angle{0.0f};
48
49// Wheel observer/plant.
50::std::atomic<StateFeedbackObserver<3, 1, 1, float> *> global_wheel_observer{
51 nullptr};
52::std::atomic<StateFeedbackPlant<3, 1, 1, float> *> global_wheel_plant{nullptr};
53// Throttle observer/plant.
54::std::atomic<StateFeedbackObserver<3, 1, 1, float> *> global_trigger_observer{
55 nullptr};
56::std::atomic<StateFeedbackPlant<3, 1, 1, float> *> global_trigger_plant{
57 nullptr};
58
59// Torques for the current loop to apply.
60::std::atomic<float> global_wheel_current{0.0f};
61::std::atomic<float> global_trigger_torque{0.0f};
62
63constexpr int kSwitchingDivisor = 2;
64
65float analog_ratio(uint16_t reading) {
66 static constexpr uint16_t kMin = 260, kMax = 3812;
67 return static_cast<float>(::std::max(::std::min(reading, kMax), kMin) -
68 kMin) /
69 static_cast<float>(kMax - kMin);
70}
71
72constexpr float InterpolateFloat(float x1, float x0, float y1, float y0, float x) {
73 return (x - x0) * (y1 - y0) / (x1 - x0) + y0;
74}
75
76float absolute_wheel(float wheel_position) {
77 if (wheel_position < 0.43f) {
78 wheel_position += 1.0f;
79 }
80 wheel_position -= 0.462f + 0.473f;
81 return wheel_position;
82}
83
84extern "C" {
85
86void *__stack_chk_guard = (void *)0x67111971;
87void __stack_chk_fail() {
88 while (true) {
89 GPIOC_PSOR = (1 << 5);
90 printf("Stack corruption detected\n");
91 delay(1000);
92 GPIOC_PCOR = (1 << 5);
93 delay(1000);
94 }
95}
96
97int _write(int /*file*/, char *ptr, int len) {
98 teensy::AcmTty *const tty = global_stdout.load(::std::memory_order_acquire);
99 if (tty != nullptr) {
100 return tty->Write(ptr, len);
101 }
102 return 0;
103}
104
105extern uint32_t __bss_ram_start__[], __bss_ram_end__[];
106extern uint32_t __data_ram_start__[], __data_ram_end__[];
107extern uint32_t __heap_start__[], __heap_end__[];
108extern uint32_t __stack_end__[];
109
110} // extern "C"
111
112constexpr float kWheelMaxExtension = 1.0f;
113constexpr float kWheelFrictionMax = 0.2f;
114float WheelCenteringCurrent(float scalar, float angle, float velocity) {
115 float friction_goal_current = -angle * 10.0f;
116 if (friction_goal_current > kWheelFrictionMax) {
117 friction_goal_current = kWheelFrictionMax;
118 } else if (friction_goal_current < -kWheelFrictionMax) {
119 friction_goal_current = -kWheelFrictionMax;
120 }
121
122 constexpr float kWheelSpringNonlinearity = 0.45f;
123
124 float goal_current = -((1.0f - kWheelSpringNonlinearity) * angle +
125 kWheelSpringNonlinearity * angle * angle * angle) *
126 6.0f -
127 velocity * 0.04f;
128 if (goal_current > 5.0f - scalar) {
129 goal_current = 5.0f - scalar;
130 } else if (goal_current < -5.0f + scalar) {
131 goal_current = -5.0f + scalar;
132 }
133
134 return goal_current * scalar + friction_goal_current;
135}
136
137extern "C" void ftm0_isr() {
138 SmallAdcReadings readings;
139 {
140 DisableInterrupts disable_interrupts;
141 readings = AdcReadSmall1(disable_interrupts);
142 }
143 uint32_t encoder =
144 global_motor1.load(::std::memory_order_relaxed)->wrapped_encoder();
145 int32_t absolute_encoder = global_motor1.load(::std::memory_order_relaxed)
146 ->absolute_encoder(encoder);
147
148 const float angle = absolute_encoder / static_cast<float>((15320 - 1488) / 2);
149 global_wheel_angle.store(angle);
150
151 float goal_current = -global_wheel_current.load(::std::memory_order_relaxed) +
152 kWheelCoggingTorque[encoder];
153
154 global_motor1.load(::std::memory_order_relaxed)->SetGoalCurrent(goal_current);
155 global_motor1.load(::std::memory_order_relaxed)
156 ->HandleInterrupt(BalanceSimpleReadings(readings.currents), encoder);
157}
158
159constexpr float kTriggerMaxExtension = -1.00f;
160constexpr float kTriggerCenter = 0.0f;
161float TriggerCenteringCurrent(float trigger_angle) {
162 float goal_current = (kTriggerCenter - trigger_angle) * 3.0f;
163 if (goal_current < -1.0f) {
164 goal_current = -1.0f;
165 } else if (goal_current > 1.0f) {
166 goal_current = 1.0f;
167 if (trigger_angle < kTriggerMaxExtension) {
168 goal_current -= (30.0f * (trigger_angle - kTriggerMaxExtension));
169 if (goal_current > 2.0f) {
170 goal_current = 2.0f;
171 }
172 }
173 }
174 return goal_current;
175}
176
177extern "C" void ftm3_isr() {
178 SmallAdcReadings readings;
179 {
180 DisableInterrupts disable_interrupts;
181 readings = AdcReadSmall0(disable_interrupts);
182 }
183 uint32_t encoder =
184 global_motor0.load(::std::memory_order_relaxed)->wrapped_encoder();
185 int32_t absolute_encoder = global_motor0.load(::std::memory_order_relaxed)
186 ->absolute_encoder(encoder);
187
188 float trigger_angle = absolute_encoder / 1370.f;
189
190 const float goal_current =
191 -global_trigger_torque.load(::std::memory_order_relaxed) +
192 kTriggerCoggingTorque[encoder];
193
194 global_motor0.load(::std::memory_order_relaxed)->SetGoalCurrent(goal_current);
195 global_motor0.load(::std::memory_order_relaxed)
196 ->HandleInterrupt(BalanceSimpleReadings(readings.currents), encoder);
197
Brian Silverman6260c092018-01-14 15:21:36 -0800198 global_trigger_angle.store(trigger_angle);
199}
200
Brian Silverman6260c092018-01-14 15:21:36 -0800201int ConvertFloat16(float val) {
202 int result = static_cast<int>(val * 32768.0f) + 32768;
203 if (result > 0xffff) {
204 result = 0xffff;
205 } else if (result < 0) {
206 result = 0;
207 }
208 return result;
209}
210int ConvertFloat14(float val) {
211 int result = static_cast<int>(val * 8192.0f) + 8192;
212 if (result > 0x3fff) {
213 result = 0x3fff;
214 } else if (result < 0) {
215 result = 0;
216 }
217 return result;
218}
219
220extern "C" void pit3_isr() {
221 PIT_TFLG3 = 1;
222 const float absolute_trigger_angle =
223 global_trigger_angle.load(::std::memory_order_relaxed);
224 const float absolute_wheel_angle =
225 global_wheel_angle.load(::std::memory_order_relaxed);
226
227 // Force a barrier here so we sample everything guaranteed at the beginning.
228 __asm__("" ::: "memory");
229 const float absolute_wheel_angle_radians =
230 absolute_wheel_angle * static_cast<float>(M_PI) * (338.16f / 360.0f);
231 const float absolute_trigger_angle_radians =
232 absolute_trigger_angle * static_cast<float>(M_PI) * (45.0f / 360.0f);
233
234 static uint32_t last_command_time = 0;
235 static float trigger_goal_position = 0.0f;
236 static float trigger_goal_velocity = 0.0f;
237 static float trigger_haptic_current = 0.0f;
238 static bool trigger_centering = true;
239 static bool trigger_haptics = false;
240 {
241 uint8_t data[8];
242 int length;
243 can_receive_command(data, &length, 0);
244 if (length > 0) {
245 last_command_time = micros();
246 trigger_goal_position =
247 static_cast<float>(
248 static_cast<int32_t>(static_cast<uint32_t>(data[0]) |
249 (static_cast<uint32_t>(data[1]) << 8)) -
250 32768) /
251 32768.0f * M_PI / 8.0;
252 trigger_goal_velocity =
253 static_cast<float>(
254 static_cast<int32_t>(static_cast<uint32_t>(data[2]) |
255 (static_cast<uint32_t>(data[3]) << 8)) -
256 32768) /
257 32768.0f * 4.0f;
258
259 trigger_haptic_current =
260 static_cast<float>(
261 static_cast<int32_t>(static_cast<uint32_t>(data[4]) |
262 (static_cast<uint32_t>(data[5]) << 8)) -
263 32768) /
264 32768.0f * 2.0f;
265 if (trigger_haptic_current > kHapticTriggerCurrentLimit) {
266 trigger_haptic_current = kHapticTriggerCurrentLimit;
267 } else if (trigger_haptic_current < -kHapticTriggerCurrentLimit) {
268 trigger_haptic_current = -kHapticTriggerCurrentLimit;
269 }
270 trigger_centering = !!(data[7] & 0x01);
271 trigger_haptics = !!(data[7] & 0x02);
272 }
273 }
274
275 static float wheel_goal_position = 0.0f;
276 static float wheel_goal_velocity = 0.0f;
277 static float wheel_haptic_current = 0.0f;
278 static float wheel_kp = 0.0f;
279 static bool wheel_centering = true;
280 static float wheel_centering_scalar = 0.25f;
281 {
282 uint8_t data[8];
283 int length;
284 can_receive_command(data, &length, 1);
285 if (length == 8) {
286 last_command_time = micros();
287 wheel_goal_position =
288 static_cast<float>(
289 static_cast<int32_t>(static_cast<uint32_t>(data[0]) |
290 (static_cast<uint32_t>(data[1]) << 8)) -
291 32768) /
292 32768.0f * M_PI;
293 wheel_goal_velocity =
294 static_cast<float>(
295 static_cast<int32_t>(static_cast<uint32_t>(data[2]) |
296 (static_cast<uint32_t>(data[3]) << 8)) -
297 32768) /
298 32768.0f * 10.0f;
299
300 wheel_haptic_current =
301 static_cast<float>(
302 static_cast<int32_t>(static_cast<uint32_t>(data[4]) |
303 (static_cast<uint32_t>(data[5]) << 8)) -
304 32768) /
305 32768.0f * 2.0f;
306 if (wheel_haptic_current > kHapticWheelCurrentLimit) {
307 wheel_haptic_current = kHapticWheelCurrentLimit;
308 } else if (wheel_haptic_current < -kHapticWheelCurrentLimit) {
309 wheel_haptic_current = -kHapticWheelCurrentLimit;
310 }
311 wheel_kp = static_cast<float>(data[6]) * 30.0f / 255.0f;
312 wheel_centering = !!(data[7] & 0x01);
313 wheel_centering_scalar = ((data[7] >> 1) & 0x7f) / 127.0f;
314 }
315 }
316
317 static constexpr uint32_t kTimeout = 100000;
318 if (!time_after(time_add(last_command_time, kTimeout), micros())) {
319 last_command_time = time_subtract(micros(), kTimeout);
320 trigger_goal_position = 0.0f;
321 trigger_goal_velocity = 0.0f;
322 trigger_haptic_current = 0.0f;
323 trigger_centering = true;
324 trigger_haptics = false;
325
326 wheel_goal_position = 0.0f;
327 wheel_goal_velocity = 0.0f;
328 wheel_haptic_current = 0.0f;
329 wheel_centering = true;
330 wheel_centering_scalar = 0.25f;
331 }
332
333 StateFeedbackPlant<3, 1, 1, float> *const trigger_plant =
334 global_trigger_plant.load(::std::memory_order_relaxed);
335 StateFeedbackObserver<3, 1, 1, float> *const trigger_observer =
336 global_trigger_observer.load(::std::memory_order_relaxed);
337 ::Eigen::Matrix<float, 1, 1> trigger_Y;
338 trigger_Y << absolute_trigger_angle_radians;
339 trigger_observer->Correct(*trigger_plant,
340 ::Eigen::Matrix<float, 1, 1>::Zero(), trigger_Y);
341
342 StateFeedbackPlant<3, 1, 1, float> *const wheel_plant =
343 global_wheel_plant.load(::std::memory_order_relaxed);
344 StateFeedbackObserver<3, 1, 1, float> *const wheel_observer =
345 global_wheel_observer.load(::std::memory_order_relaxed);
346 ::Eigen::Matrix<float, 1, 1> wheel_Y;
347 wheel_Y << absolute_wheel_angle_radians;
348 wheel_observer->Correct(*wheel_plant, ::Eigen::Matrix<float, 1, 1>::Zero(),
349 wheel_Y);
350
351 float kWheelD = (wheel_kp - 10.0f) * (0.25f - 0.20f) / 5.0f + 0.20f;
352 if (wheel_kp < 0.5f) {
353 kWheelD = wheel_kp * 0.05f / 0.5f;
354 } else if (wheel_kp < 1.0f) {
355 kWheelD = InterpolateFloat(1.0f, 0.5f, 0.06f, 0.05f, wheel_kp);
356 } else if (wheel_kp < 2.0f) {
357 kWheelD = InterpolateFloat(2.0f, 1.0f, 0.08f, 0.06f, wheel_kp);
358 } else if (wheel_kp < 3.0f) {
359 kWheelD = InterpolateFloat(3.0f, 2.0f, 0.10f, 0.08f, wheel_kp);
360 } else if (wheel_kp < 5.0f) {
361 kWheelD = InterpolateFloat(5.0f, 3.0f, 0.13f, 0.10f, wheel_kp);
362 } else if (wheel_kp < 10.0f) {
363 kWheelD = InterpolateFloat(10.0f, 5.0f, 0.20f, 0.13f, wheel_kp);
364 }
365
366 float wheel_goal_current = wheel_haptic_current;
367
368 wheel_goal_current +=
369 (wheel_goal_position - absolute_wheel_angle_radians) * wheel_kp +
370 (wheel_goal_velocity - wheel_observer->X_hat()(1, 0)) * kWheelD;
371
372 // Compute the torques to apply to each motor.
373 if (wheel_centering) {
374 wheel_goal_current +=
375 WheelCenteringCurrent(wheel_centering_scalar, absolute_wheel_angle,
376 wheel_observer->X_hat()(1, 0));
377 }
378
379 if (wheel_goal_current > kHapticWheelCurrentLimit) {
380 wheel_goal_current = kHapticWheelCurrentLimit;
381 } else if (wheel_goal_current < -kHapticWheelCurrentLimit) {
382 wheel_goal_current = -kHapticWheelCurrentLimit;
383 }
384 global_wheel_current.store(wheel_goal_current, ::std::memory_order_relaxed);
385
386 constexpr float kTriggerP =
387 static_cast<float>(::frc971::control_loops::drivetrain::kHapticTriggerP);
388 constexpr float kTriggerD =
389 static_cast<float>(::frc971::control_loops::drivetrain::kHapticTriggerD);
390 float trigger_goal_current = trigger_haptic_current;
391 if (trigger_haptics) {
392 trigger_goal_current +=
393 (trigger_goal_position - absolute_trigger_angle_radians) * kTriggerP +
394 (trigger_goal_velocity - trigger_observer->X_hat()(1, 0)) * kTriggerD;
395 }
396
397 if (trigger_centering) {
398 trigger_goal_current += TriggerCenteringCurrent(absolute_trigger_angle);
399 }
400
401 if (trigger_goal_current > kHapticTriggerCurrentLimit) {
402 trigger_goal_current = kHapticTriggerCurrentLimit;
403 } else if (trigger_goal_current < -kHapticTriggerCurrentLimit) {
404 trigger_goal_current = -kHapticTriggerCurrentLimit;
405 }
406 global_trigger_torque.store(trigger_goal_current,
407 ::std::memory_order_relaxed);
408
409 uint8_t buttons = 0;
410 if (!GPIO_BITBAND(GPIOA_PDIR, 14)) {
411 buttons |= 0x1;
412 }
413 if (!GPIO_BITBAND(GPIOE_PDIR, 26)) {
414 buttons |= 0x2;
415 }
416 if (!GPIO_BITBAND(GPIOC_PDIR, 7)) {
417 buttons |= 0x4;
418 }
419 if (!GPIO_BITBAND(GPIOD_PDIR, 0)) {
420 buttons |= 0x8;
421 }
422
423 float trigger_angle = absolute_trigger_angle;
424
425 // Adjust the trigger range for reporting back.
426 // TODO(austin): We'll likely need to make this symmetric for the controls to
427 // work out well.
428 if (trigger_angle > kTriggerCenter) {
429 trigger_angle = (trigger_angle - kTriggerCenter) / (1.0f - kTriggerCenter);
430 } else {
431 trigger_angle = (trigger_angle - kTriggerCenter) /
432 (kTriggerCenter - kTriggerMaxExtension);
433 }
434
435 // TODO(austin): Class + fns. This is a mess.
436 // TODO(austin): Move this to a separate file. It's too big.
437 int can_trigger = ConvertFloat16(absolute_trigger_angle);
438 int can_trigger_velocity =
439 ConvertFloat16(trigger_observer->X_hat()(1, 0) / 50.0f);
440 int can_trigger_torque =
441 ConvertFloat16(trigger_observer->X_hat()(2, 0) * 2.0f);
442 int can_trigger_current = ConvertFloat14(trigger_goal_current / 10.0f);
443
444 int can_wheel = ConvertFloat16(absolute_wheel_angle);
445 int can_wheel_velocity =
446 ConvertFloat16(wheel_observer->X_hat()(1, 0) / 50.0f);
447 int can_wheel_torque = ConvertFloat16(wheel_observer->X_hat()(2, 0) * 2.0f);
448 int can_wheel_current = ConvertFloat14(wheel_goal_current / 10.0f);
449
450 {
451 const uint8_t trigger_joystick_values[8] = {
452 static_cast<uint8_t>(can_trigger & 0xff),
453 static_cast<uint8_t>((can_trigger >> 8) & 0xff),
454 static_cast<uint8_t>(can_trigger_velocity & 0xff),
455 static_cast<uint8_t>((can_trigger_velocity >> 8) & 0xff),
456 static_cast<uint8_t>(can_trigger_torque & 0xff),
457 static_cast<uint8_t>((can_trigger_torque >> 8) & 0xff),
458 static_cast<uint8_t>(can_trigger_current & 0xff),
459 static_cast<uint8_t>(((buttons & 0x3) << 6) |
460 (can_trigger_current >> 8))};
461 const uint8_t wheel_joystick_values[8] = {
462 static_cast<uint8_t>(can_wheel & 0xff),
463 static_cast<uint8_t>((can_wheel >> 8) & 0xff),
464 static_cast<uint8_t>(can_wheel_velocity & 0xff),
465 static_cast<uint8_t>((can_wheel_velocity >> 8) & 0xff),
466 static_cast<uint8_t>(can_wheel_torque & 0xff),
467 static_cast<uint8_t>((can_wheel_torque >> 8) & 0xff),
468 static_cast<uint8_t>(can_wheel_current & 0xff),
469 static_cast<uint8_t>(((buttons & 0xc) << 4) |
470 (can_wheel_current >> 8))};
471
472 can_send(0, trigger_joystick_values, 8, 2);
473 can_send(1, wheel_joystick_values, 8, 3);
474 }
475
476 ::Eigen::Matrix<float, 1, 1> trigger_U;
477 trigger_U << trigger_goal_current;
478 ::Eigen::Matrix<float, 1, 1> wheel_U;
479 wheel_U << wheel_goal_current;
480 trigger_observer->Predict(trigger_plant, trigger_U,
481 ::std::chrono::milliseconds(1));
482 wheel_observer->Predict(wheel_plant, wheel_U, ::std::chrono::milliseconds(1));
483}
484
485void ConfigurePwmFtm(BigFTM *pwm_ftm) {
486 // Put them all into combine active-high mode, and all the low ones staying
487 // off all the time by default. We'll then use only the low ones.
488 pwm_ftm->C0SC = FTM_CSC_ELSB;
489 pwm_ftm->C0V = 0;
490 pwm_ftm->C1SC = FTM_CSC_ELSB;
491 pwm_ftm->C1V = 0;
492 pwm_ftm->C2SC = FTM_CSC_ELSB;
493 pwm_ftm->C2V = 0;
494 pwm_ftm->C3SC = FTM_CSC_ELSB;
495 pwm_ftm->C3V = 0;
496 pwm_ftm->C4SC = FTM_CSC_ELSB;
497 pwm_ftm->C4V = 0;
498 pwm_ftm->C5SC = FTM_CSC_ELSB;
499 pwm_ftm->C5V = 0;
500 pwm_ftm->C6SC = FTM_CSC_ELSB;
501 pwm_ftm->C6V = 0;
502 pwm_ftm->C7SC = FTM_CSC_ELSB;
503 pwm_ftm->C7V = 0;
504
505 pwm_ftm->COMBINE = FTM_COMBINE_SYNCEN3 /* Synchronize updates usefully */ |
506 FTM_COMBINE_COMP3 /* Make them complementary */ |
507 FTM_COMBINE_COMBINE3 /* Combine the channels */ |
508 FTM_COMBINE_SYNCEN2 /* Synchronize updates usefully */ |
509 FTM_COMBINE_COMP2 /* Make them complementary */ |
510 FTM_COMBINE_COMBINE2 /* Combine the channels */ |
511 FTM_COMBINE_SYNCEN1 /* Synchronize updates usefully */ |
512 FTM_COMBINE_COMP1 /* Make them complementary */ |
513 FTM_COMBINE_COMBINE1 /* Combine the channels */ |
514 FTM_COMBINE_SYNCEN0 /* Synchronize updates usefully */ |
515 FTM_COMBINE_COMP0 /* Make them complementary */ |
516 FTM_COMBINE_COMBINE0 /* Combine the channels */;
517}
518
519bool CountValid(uint32_t count) {
520 static constexpr int kMaxMovement = 1;
521 return count <= kMaxMovement || count >= (4096 - kMaxMovement);
522}
523
524bool ZeroMotors(uint16_t *motor0_offset, uint16_t *motor1_offset,
525 uint16_t *wheel_offset) {
526 static constexpr int kNumberSamples = 1024;
527 static_assert(UINT16_MAX * kNumberSamples <= UINT32_MAX, "Too many samples");
528 uint32_t motor0_sum = 0, motor1_sum = 0, wheel_sum = 0;
529
530 // First clear both encoders.
531 MOTOR0_ENCODER_FTM->CNT = MOTOR1_ENCODER_FTM->CNT = 0;
532 for (int i = 0; i < kNumberSamples; ++i) {
533 delay(1);
534
535 if (!CountValid(MOTOR0_ENCODER_FTM->CNT)) {
536 printf("Motor 0 moved too much\n");
537 return false;
538 }
539 if (!CountValid(MOTOR1_ENCODER_FTM->CNT)) {
540 printf("Motor 1 moved too much\n");
541 return false;
542 }
543
544 DisableInterrupts disable_interrupts;
545 const SmallInitReadings readings = AdcReadSmallInit(disable_interrupts);
546 motor0_sum += readings.motor0_abs;
547 motor1_sum += readings.motor1_abs;
548 wheel_sum += readings.wheel_abs;
549 }
550
551 *motor0_offset = (motor0_sum + kNumberSamples / 2) / kNumberSamples;
552 *motor1_offset = (motor1_sum + kNumberSamples / 2) / kNumberSamples;
553 *wheel_offset = (wheel_sum + kNumberSamples / 2) / kNumberSamples;
554
555 return true;
556}
557
558} // namespace
559
560extern "C" int main() {
561 // for background about this startup delay, please see these conversations
562 // https://forum.pjrc.com/threads/36606-startup-time-(400ms)?p=113980&viewfull=1#post113980
563 // https://forum.pjrc.com/threads/31290-Teensey-3-2-Teensey-Loader-1-24-Issues?p=87273&viewfull=1#post87273
564 delay(400);
565
566 // Set all interrupts to the second-lowest priority to start with.
567 for (int i = 0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_SANE_PRIORITY(i, 0xD);
568
569 // Now set priorities for all the ones we care about. They only have meaning
570 // relative to each other, which means centralizing them here makes it a lot
571 // more manageable.
572 NVIC_SET_SANE_PRIORITY(IRQ_USBOTG, 0x7);
573 NVIC_SET_SANE_PRIORITY(IRQ_FTM0, 0x3);
574 NVIC_SET_SANE_PRIORITY(IRQ_FTM3, 0x3);
575 NVIC_SET_SANE_PRIORITY(IRQ_PIT_CH3, 0x5);
576
577 // Set the LED's pin to output mode.
578 GPIO_BITBAND(GPIOC_PDDR, 5) = 1;
579 PORTC_PCR5 = PORT_PCR_DSE | PORT_PCR_MUX(1);
580
581 // Set up the CAN pins.
582 PORTA_PCR12 = PORT_PCR_DSE | PORT_PCR_MUX(2);
583 PORTA_PCR13 = PORT_PCR_DSE | PORT_PCR_MUX(2);
584
585 // BTN0
586 PORTC_PCR7 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
587 // BTN1
588 PORTE_PCR26 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
589 // BTN2
590 PORTA_PCR14 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
591 // BTN3
592 PORTD_PCR0 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
593
594 PORTA_PCR5 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
595
596 DMA_CR = DMA_CR_EMLM;
597
598 teensy::UsbDevice usb_device(0, 0x16c0, 0x0490);
599 usb_device.SetManufacturer("FRC 971 Spartan Robotics");
600 usb_device.SetProduct("Pistol Grip Controller debug");
601 teensy::AcmTty tty1(&usb_device);
602 teensy::AcmTty tty2(&usb_device);
603 global_stdout.store(&tty1, ::std::memory_order_release);
604 usb_device.Initialize();
605
606 AdcInitSmall();
607 MathInit();
608 delay(100);
609 can_init(2, 3);
610
611 GPIOD_PCOR = 1 << 3;
612 GPIO_BITBAND(GPIOD_PDDR, 3) = 1;
613 PORTD_PCR3 = PORT_PCR_DSE | PORT_PCR_MUX(1);
614 GPIOD_PSOR = 1 << 3;
615
616 GPIOC_PCOR = 1 << 4;
617 GPIO_BITBAND(GPIOC_PDDR, 4) = 1;
618 PORTC_PCR4 = PORT_PCR_DSE | PORT_PCR_MUX(1);
619 GPIOC_PSOR = 1 << 4;
620
621 LittleMotorControlsImplementation controls0, controls1;
622
623 delay(100);
624
625 // M0_EA = FTM1_QD_PHB
626 PORTB_PCR19 = PORT_PCR_MUX(6);
627 // M0_EB = FTM1_QD_PHA
628 PORTB_PCR18 = PORT_PCR_MUX(6);
629
630 // M1_EA = FTM1_QD_PHA
631 PORTB_PCR0 = PORT_PCR_MUX(6);
632 // M1_EB = FTM1_QD_PHB
633 PORTB_PCR1 = PORT_PCR_MUX(6);
634
635 // M0_CH0 = FTM3_CH4
636 PORTC_PCR8 = PORT_PCR_DSE | PORT_PCR_MUX(3);
637 // M0_CH1 = FTM3_CH2
638 PORTD_PCR2 = PORT_PCR_DSE | PORT_PCR_MUX(4);
639 // M0_CH2 = FTM3_CH6
640 PORTC_PCR10 = PORT_PCR_DSE | PORT_PCR_MUX(3);
641
642 // M1_CH0 = FTM0_CH0
643 PORTC_PCR1 = PORT_PCR_DSE | PORT_PCR_MUX(4);
644 // M1_CH1 = FTM0_CH2
645 PORTC_PCR3 = PORT_PCR_DSE | PORT_PCR_MUX(4);
646 // M1_CH2 = FTM0_CH4
647 PORTD_PCR4 = PORT_PCR_DSE | PORT_PCR_MUX(4);
648
649 Motor motor0(
650 MOTOR0_PWM_FTM, MOTOR0_ENCODER_FTM, &controls0,
651 {&MOTOR0_PWM_FTM->C4V, &MOTOR0_PWM_FTM->C2V, &MOTOR0_PWM_FTM->C6V});
652 motor0.set_debug_tty(&tty2);
653 motor0.set_switching_divisor(kSwitchingDivisor);
654 Motor motor1(
655 MOTOR1_PWM_FTM, MOTOR1_ENCODER_FTM, &controls1,
656 {&MOTOR1_PWM_FTM->C0V, &MOTOR1_PWM_FTM->C2V, &MOTOR1_PWM_FTM->C4V});
657 motor1.set_debug_tty(&tty2);
658 motor1.set_switching_divisor(kSwitchingDivisor);
659 ConfigurePwmFtm(MOTOR0_PWM_FTM);
660 ConfigurePwmFtm(MOTOR1_PWM_FTM);
661 motor0.Init();
662 motor1.Init();
663 global_motor0.store(&motor0, ::std::memory_order_relaxed);
664 global_motor1.store(&motor1, ::std::memory_order_relaxed);
665
666 SIM_SCGC6 |= SIM_SCGC6_PIT;
667 PIT_MCR = 0;
668 PIT_LDVAL3 = BUS_CLOCK_FREQUENCY / 1000;
669 PIT_TCTRL3 = PIT_TCTRL_TIE | PIT_TCTRL_TEN;
670
671 // Have them both wait for the GTB signal.
672 FTM0->CONF = FTM3->CONF =
673 FTM_CONF_GTBEEN | FTM_CONF_NUMTOF(kSwitchingDivisor - 1);
674 // Make FTM3's period half of what it should be so we can get it a half-cycle
675 // out of phase.
676 const uint32_t original_mod = FTM3->MOD;
677 FTM3->MOD = ((original_mod + 1) / 2) - 1;
678 FTM3->SYNC |= FTM_SYNC_SWSYNC;
679
680 // Output triggers to things like the PDBs on initialization.
681 FTM0_EXTTRIG = FTM_EXTTRIG_INITTRIGEN;
682 FTM3_EXTTRIG = FTM_EXTTRIG_INITTRIGEN;
683 // Don't let any memory accesses sneak past here, because we actually
684 // need everything to be starting up.
685 __asm__("" ::: "memory");
686
687 // Give everything a chance to get going.
688 delay(100);
689
690 printf("BSS: %p-%p\n", __bss_ram_start__, __bss_ram_end__);
691 printf("data: %p-%p\n", __data_ram_start__, __data_ram_end__);
692 printf("heap start: %p\n", __heap_start__);
693 printf("stack start: %p\n", __stack_end__);
694
695 printf("Zeroing motors\n");
696 uint16_t motor0_offset, motor1_offset, wheel_offset;
697 while (!ZeroMotors(&motor0_offset, &motor1_offset, &wheel_offset)) {
698 }
699 printf("Done zeroing\n");
700
701 const float motor0_offset_scaled = -analog_ratio(motor0_offset);
702 const float motor1_offset_scaled = analog_ratio(motor1_offset);
703 // Good for the initial trigger.
704 {
705 constexpr float kZeroOffset0 = 0.27f;
706 const int motor0_starting_point = static_cast<int>(
707 (motor0_offset_scaled + (kZeroOffset0 / 7.0f)) * 4096.0f);
708 printf("Motor 0 starting at %d\n", motor0_starting_point);
709 motor0.set_encoder_calibration_offset(motor0_starting_point);
710 motor0.set_encoder_multiplier(-1);
711
712 // Calibrate neutral here.
713 motor0.set_encoder_offset(motor0.encoder_offset() - 2065 + 20);
714
715 uint32_t new_encoder = motor0.wrapped_encoder();
716 int32_t absolute_encoder = motor0.absolute_encoder(new_encoder);
717 printf("Motor 0 encoder %d absolute %d\n", static_cast<int>(new_encoder),
718 static_cast<int>(absolute_encoder));
719 }
720
721 {
722 constexpr float kZeroOffset1 = 0.26f;
723 const int motor1_starting_point = static_cast<int>(
724 (motor1_offset_scaled + (kZeroOffset1 / 7.0f)) * 4096.0f);
725 printf("Motor 1 starting at %d\n", motor1_starting_point);
726 motor1.set_encoder_calibration_offset(motor1_starting_point);
727 motor1.set_encoder_multiplier(-1);
728
729 float wheel_position = absolute_wheel(analog_ratio(wheel_offset));
730
731 uint32_t encoder = motor1.wrapped_encoder();
732
733 printf("Wheel starting at %d, encoder %" PRId32 "\n",
734 static_cast<int>(wheel_position * 1000.0f), encoder);
735
736 constexpr float kWheelGearRatio = (1.25f + 0.02f) / 0.35f;
737 constexpr float kWrappedWheelAtZero = 0.6586310546875f;
738
739 const int encoder_wraps =
740 static_cast<int>(lround(wheel_position * kWheelGearRatio -
741 (encoder / 4096.f) + kWrappedWheelAtZero));
742
743 printf("Wraps: %d\n", encoder_wraps);
744 motor1.set_encoder_offset(4096 * encoder_wraps + motor1.encoder_offset() -
745 static_cast<int>(kWrappedWheelAtZero * 4096));
746 printf("Wheel encoder now at %d\n",
747 static_cast<int>(1000.f / 4096.f *
748 motor1.absolute_encoder(motor1.wrapped_encoder())));
749 }
750
751 // Turn an LED on for Austin.
752 GPIO_BITBAND(GPIOC_PDDR, 6) = 1;
753 GPIOC_PCOR = 1 << 6;
754 PORTC_PCR6 = PORT_PCR_DSE | PORT_PCR_MUX(1);
755
756 // M0_THW
757 PORTC_PCR11 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
758 // M0_FAULT
759 PORTD_PCR6 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
760 // M1_THW
761 PORTC_PCR2 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
762 // M1_FAULT
763 PORTD_PCR5 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
764
765 motor0.Start();
766 motor1.Start();
767 {
768 // We rely on various things happening faster than the timer period, so make
769 // sure slow USB or whatever interrupts don't prevent that.
770 DisableInterrupts disable_interrupts;
771
772 // First clear the overflow flag.
773 FTM3->SC &= ~FTM_SC_TOF;
774
775 // Now poke the GTB to actually start both timers.
776 FTM0->CONF = FTM_CONF_GTBEEN | FTM_CONF_GTBEOUT |
777 FTM_CONF_NUMTOF(kSwitchingDivisor - 1);
778
779 // Wait for it to overflow twice. For some reason, just once doesn't work.
780 while (!(FTM3->SC & FTM_SC_TOF)) {
781 }
782 FTM3->SC &= ~FTM_SC_TOF;
783 while (!(FTM3->SC & FTM_SC_TOF)) {
784 }
785
786 // Now put the MOD value back to what it was.
787 FTM3->MOD = original_mod;
788 FTM3->PWMLOAD = FTM_PWMLOAD_LDOK;
789
790 // And then clear the overflow flags before enabling interrupts so we
791 // actually wait until the next overflow to start doing interrupts.
792 FTM0->SC &= ~FTM_SC_TOF;
793 FTM3->SC &= ~FTM_SC_TOF;
794 NVIC_ENABLE_IRQ(IRQ_FTM0);
795 NVIC_ENABLE_IRQ(IRQ_FTM3);
796 }
797 global_trigger_plant.store(
798 new StateFeedbackPlant<3, 1, 1, float>(MakeIntegralHapticTriggerPlant()));
799 global_trigger_observer.store(new StateFeedbackObserver<3, 1, 1, float>(
800 MakeIntegralHapticTriggerObserver()));
801 global_trigger_observer.load(::std::memory_order_relaxed)
802 ->Reset(global_trigger_plant.load(::std::memory_order_relaxed));
803
804 global_wheel_plant.store(
805 new StateFeedbackPlant<3, 1, 1, float>(MakeIntegralHapticWheelPlant()));
806 global_wheel_observer.store(new StateFeedbackObserver<3, 1, 1, float>(
807 MakeIntegralHapticWheelObserver()));
808 global_wheel_observer.load(::std::memory_order_relaxed)
809 ->Reset(global_wheel_plant.load(::std::memory_order_relaxed));
810
811 delay(1000);
812
813 NVIC_ENABLE_IRQ(IRQ_PIT_CH3);
814
815 // TODO(Brian): Use SLEEPONEXIT to reduce interrupt latency?
816 while (true) {
817 if (!GPIO_BITBAND(GPIOC_PDIR, 11)) {
818 if (!GPIO_BITBAND(GPIOC_PDOR, 5)) {
819 printf("M0_THW\n");
820 }
821 GPIOC_PSOR = 1 << 5;
822 }
823 if (!GPIO_BITBAND(GPIOD_PDIR, 6)) {
824 if (!GPIO_BITBAND(GPIOC_PDOR, 5)) {
825 printf("M0_FAULT\n");
826 }
827 GPIOC_PSOR = 1 << 5;
828 }
829 if (!GPIO_BITBAND(GPIOC_PDIR, 2)) {
830 if (!GPIO_BITBAND(GPIOC_PDOR, 5)) {
831 printf("M1_THW\n");
832 }
833 GPIOC_PSOR = 1 << 5;
834 }
835 if (!GPIO_BITBAND(GPIOD_PDIR, 5)) {
836 if (!GPIO_BITBAND(GPIOC_PDOR, 5)) {
837 printf("M1_FAULT\n");
838 }
839 GPIOC_PSOR = 1 << 5;
840 }
841 }
842
843 return 0;
844}
845
846} // namespace salsa
847} // namespace frc971