blob: 162ac2fb79aabc8a1183d17a9059af432261e3a3 [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
Austin Schuh876b4f02018-03-10 19:16:59 -0800159constexpr float kTriggerMaxExtension = -0.70f;
Brian Silverman6260c092018-01-14 15:21:36 -0800160constexpr float kTriggerCenter = 0.0f;
Austin Schuh876b4f02018-03-10 19:16:59 -0800161constexpr float kCenteringStiffness = 0.15f;
Brian Silverman6260c092018-01-14 15:21:36 -0800162float TriggerCenteringCurrent(float trigger_angle) {
163 float goal_current = (kTriggerCenter - trigger_angle) * 3.0f;
Austin Schuh876b4f02018-03-10 19:16:59 -0800164 float knotch_goal_current = (kTriggerCenter - trigger_angle) * 8.0f;
165 if (knotch_goal_current < -kCenteringStiffness) {
166 knotch_goal_current = -kCenteringStiffness;
167 } else if (knotch_goal_current > kCenteringStiffness) {
168 knotch_goal_current = kCenteringStiffness;
169 }
170
171 goal_current += knotch_goal_current;
172
Brian Silverman6260c092018-01-14 15:21:36 -0800173 if (goal_current < -1.0f) {
174 goal_current = -1.0f;
175 } else if (goal_current > 1.0f) {
176 goal_current = 1.0f;
177 if (trigger_angle < kTriggerMaxExtension) {
178 goal_current -= (30.0f * (trigger_angle - kTriggerMaxExtension));
Austin Schuh876b4f02018-03-10 19:16:59 -0800179 if (goal_current > 4.0f) {
180 goal_current = 4.0f;
Brian Silverman6260c092018-01-14 15:21:36 -0800181 }
182 }
183 }
184 return goal_current;
185}
186
187extern "C" void ftm3_isr() {
188 SmallAdcReadings readings;
189 {
190 DisableInterrupts disable_interrupts;
191 readings = AdcReadSmall0(disable_interrupts);
192 }
193 uint32_t encoder =
194 global_motor0.load(::std::memory_order_relaxed)->wrapped_encoder();
195 int32_t absolute_encoder = global_motor0.load(::std::memory_order_relaxed)
196 ->absolute_encoder(encoder);
197
198 float trigger_angle = absolute_encoder / 1370.f;
199
200 const float goal_current =
201 -global_trigger_torque.load(::std::memory_order_relaxed) +
202 kTriggerCoggingTorque[encoder];
203
204 global_motor0.load(::std::memory_order_relaxed)->SetGoalCurrent(goal_current);
205 global_motor0.load(::std::memory_order_relaxed)
206 ->HandleInterrupt(BalanceSimpleReadings(readings.currents), encoder);
207
Brian Silverman6260c092018-01-14 15:21:36 -0800208 global_trigger_angle.store(trigger_angle);
209}
210
Brian Silverman6260c092018-01-14 15:21:36 -0800211int ConvertFloat16(float val) {
212 int result = static_cast<int>(val * 32768.0f) + 32768;
213 if (result > 0xffff) {
214 result = 0xffff;
215 } else if (result < 0) {
216 result = 0;
217 }
218 return result;
219}
220int ConvertFloat14(float val) {
221 int result = static_cast<int>(val * 8192.0f) + 8192;
222 if (result > 0x3fff) {
223 result = 0x3fff;
224 } else if (result < 0) {
225 result = 0;
226 }
227 return result;
228}
229
230extern "C" void pit3_isr() {
231 PIT_TFLG3 = 1;
232 const float absolute_trigger_angle =
233 global_trigger_angle.load(::std::memory_order_relaxed);
234 const float absolute_wheel_angle =
235 global_wheel_angle.load(::std::memory_order_relaxed);
236
237 // Force a barrier here so we sample everything guaranteed at the beginning.
238 __asm__("" ::: "memory");
239 const float absolute_wheel_angle_radians =
240 absolute_wheel_angle * static_cast<float>(M_PI) * (338.16f / 360.0f);
241 const float absolute_trigger_angle_radians =
242 absolute_trigger_angle * static_cast<float>(M_PI) * (45.0f / 360.0f);
243
244 static uint32_t last_command_time = 0;
245 static float trigger_goal_position = 0.0f;
246 static float trigger_goal_velocity = 0.0f;
247 static float trigger_haptic_current = 0.0f;
248 static bool trigger_centering = true;
249 static bool trigger_haptics = false;
250 {
251 uint8_t data[8];
252 int length;
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700253 can_receive(data, &length, 0);
Brian Silverman6260c092018-01-14 15:21:36 -0800254 if (length > 0) {
255 last_command_time = micros();
256 trigger_goal_position =
257 static_cast<float>(
258 static_cast<int32_t>(static_cast<uint32_t>(data[0]) |
259 (static_cast<uint32_t>(data[1]) << 8)) -
260 32768) /
261 32768.0f * M_PI / 8.0;
262 trigger_goal_velocity =
263 static_cast<float>(
264 static_cast<int32_t>(static_cast<uint32_t>(data[2]) |
265 (static_cast<uint32_t>(data[3]) << 8)) -
266 32768) /
267 32768.0f * 4.0f;
268
269 trigger_haptic_current =
270 static_cast<float>(
271 static_cast<int32_t>(static_cast<uint32_t>(data[4]) |
272 (static_cast<uint32_t>(data[5]) << 8)) -
273 32768) /
274 32768.0f * 2.0f;
275 if (trigger_haptic_current > kHapticTriggerCurrentLimit) {
276 trigger_haptic_current = kHapticTriggerCurrentLimit;
277 } else if (trigger_haptic_current < -kHapticTriggerCurrentLimit) {
278 trigger_haptic_current = -kHapticTriggerCurrentLimit;
279 }
280 trigger_centering = !!(data[7] & 0x01);
281 trigger_haptics = !!(data[7] & 0x02);
282 }
283 }
284
285 static float wheel_goal_position = 0.0f;
286 static float wheel_goal_velocity = 0.0f;
287 static float wheel_haptic_current = 0.0f;
288 static float wheel_kp = 0.0f;
289 static bool wheel_centering = true;
290 static float wheel_centering_scalar = 0.25f;
291 {
292 uint8_t data[8];
293 int length;
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700294 can_receive(data, &length, 1);
Brian Silverman6260c092018-01-14 15:21:36 -0800295 if (length == 8) {
296 last_command_time = micros();
297 wheel_goal_position =
298 static_cast<float>(
299 static_cast<int32_t>(static_cast<uint32_t>(data[0]) |
300 (static_cast<uint32_t>(data[1]) << 8)) -
301 32768) /
302 32768.0f * M_PI;
303 wheel_goal_velocity =
304 static_cast<float>(
305 static_cast<int32_t>(static_cast<uint32_t>(data[2]) |
306 (static_cast<uint32_t>(data[3]) << 8)) -
307 32768) /
308 32768.0f * 10.0f;
309
310 wheel_haptic_current =
311 static_cast<float>(
312 static_cast<int32_t>(static_cast<uint32_t>(data[4]) |
313 (static_cast<uint32_t>(data[5]) << 8)) -
314 32768) /
315 32768.0f * 2.0f;
316 if (wheel_haptic_current > kHapticWheelCurrentLimit) {
317 wheel_haptic_current = kHapticWheelCurrentLimit;
318 } else if (wheel_haptic_current < -kHapticWheelCurrentLimit) {
319 wheel_haptic_current = -kHapticWheelCurrentLimit;
320 }
321 wheel_kp = static_cast<float>(data[6]) * 30.0f / 255.0f;
322 wheel_centering = !!(data[7] & 0x01);
323 wheel_centering_scalar = ((data[7] >> 1) & 0x7f) / 127.0f;
324 }
325 }
326
327 static constexpr uint32_t kTimeout = 100000;
328 if (!time_after(time_add(last_command_time, kTimeout), micros())) {
329 last_command_time = time_subtract(micros(), kTimeout);
330 trigger_goal_position = 0.0f;
331 trigger_goal_velocity = 0.0f;
332 trigger_haptic_current = 0.0f;
333 trigger_centering = true;
334 trigger_haptics = false;
335
336 wheel_goal_position = 0.0f;
337 wheel_goal_velocity = 0.0f;
338 wheel_haptic_current = 0.0f;
339 wheel_centering = true;
340 wheel_centering_scalar = 0.25f;
Brian Silverman17ffa8c2018-03-09 18:27:29 -0800341 // Avoid wrapping back into the valid range.
342 last_command_time = time_subtract(micros(), kTimeout);
Brian Silverman6260c092018-01-14 15:21:36 -0800343 }
344
345 StateFeedbackPlant<3, 1, 1, float> *const trigger_plant =
346 global_trigger_plant.load(::std::memory_order_relaxed);
347 StateFeedbackObserver<3, 1, 1, float> *const trigger_observer =
348 global_trigger_observer.load(::std::memory_order_relaxed);
349 ::Eigen::Matrix<float, 1, 1> trigger_Y;
350 trigger_Y << absolute_trigger_angle_radians;
351 trigger_observer->Correct(*trigger_plant,
352 ::Eigen::Matrix<float, 1, 1>::Zero(), trigger_Y);
353
354 StateFeedbackPlant<3, 1, 1, float> *const wheel_plant =
355 global_wheel_plant.load(::std::memory_order_relaxed);
356 StateFeedbackObserver<3, 1, 1, float> *const wheel_observer =
357 global_wheel_observer.load(::std::memory_order_relaxed);
358 ::Eigen::Matrix<float, 1, 1> wheel_Y;
359 wheel_Y << absolute_wheel_angle_radians;
360 wheel_observer->Correct(*wheel_plant, ::Eigen::Matrix<float, 1, 1>::Zero(),
361 wheel_Y);
362
363 float kWheelD = (wheel_kp - 10.0f) * (0.25f - 0.20f) / 5.0f + 0.20f;
364 if (wheel_kp < 0.5f) {
365 kWheelD = wheel_kp * 0.05f / 0.5f;
366 } else if (wheel_kp < 1.0f) {
367 kWheelD = InterpolateFloat(1.0f, 0.5f, 0.06f, 0.05f, wheel_kp);
368 } else if (wheel_kp < 2.0f) {
369 kWheelD = InterpolateFloat(2.0f, 1.0f, 0.08f, 0.06f, wheel_kp);
370 } else if (wheel_kp < 3.0f) {
371 kWheelD = InterpolateFloat(3.0f, 2.0f, 0.10f, 0.08f, wheel_kp);
372 } else if (wheel_kp < 5.0f) {
373 kWheelD = InterpolateFloat(5.0f, 3.0f, 0.13f, 0.10f, wheel_kp);
374 } else if (wheel_kp < 10.0f) {
375 kWheelD = InterpolateFloat(10.0f, 5.0f, 0.20f, 0.13f, wheel_kp);
376 }
377
378 float wheel_goal_current = wheel_haptic_current;
379
380 wheel_goal_current +=
381 (wheel_goal_position - absolute_wheel_angle_radians) * wheel_kp +
382 (wheel_goal_velocity - wheel_observer->X_hat()(1, 0)) * kWheelD;
383
384 // Compute the torques to apply to each motor.
385 if (wheel_centering) {
386 wheel_goal_current +=
387 WheelCenteringCurrent(wheel_centering_scalar, absolute_wheel_angle,
388 wheel_observer->X_hat()(1, 0));
389 }
390
391 if (wheel_goal_current > kHapticWheelCurrentLimit) {
392 wheel_goal_current = kHapticWheelCurrentLimit;
393 } else if (wheel_goal_current < -kHapticWheelCurrentLimit) {
394 wheel_goal_current = -kHapticWheelCurrentLimit;
395 }
396 global_wheel_current.store(wheel_goal_current, ::std::memory_order_relaxed);
397
398 constexpr float kTriggerP =
399 static_cast<float>(::frc971::control_loops::drivetrain::kHapticTriggerP);
400 constexpr float kTriggerD =
401 static_cast<float>(::frc971::control_loops::drivetrain::kHapticTriggerD);
402 float trigger_goal_current = trigger_haptic_current;
403 if (trigger_haptics) {
404 trigger_goal_current +=
405 (trigger_goal_position - absolute_trigger_angle_radians) * kTriggerP +
406 (trigger_goal_velocity - trigger_observer->X_hat()(1, 0)) * kTriggerD;
407 }
408
409 if (trigger_centering) {
410 trigger_goal_current += TriggerCenteringCurrent(absolute_trigger_angle);
411 }
412
413 if (trigger_goal_current > kHapticTriggerCurrentLimit) {
414 trigger_goal_current = kHapticTriggerCurrentLimit;
415 } else if (trigger_goal_current < -kHapticTriggerCurrentLimit) {
416 trigger_goal_current = -kHapticTriggerCurrentLimit;
417 }
418 global_trigger_torque.store(trigger_goal_current,
419 ::std::memory_order_relaxed);
420
421 uint8_t buttons = 0;
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500422 if (!PERIPHERAL_BITBAND(GPIOA_PDIR, 14)) {
Brian Silverman6260c092018-01-14 15:21:36 -0800423 buttons |= 0x1;
424 }
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500425 if (!PERIPHERAL_BITBAND(GPIOE_PDIR, 26)) {
Brian Silverman6260c092018-01-14 15:21:36 -0800426 buttons |= 0x2;
427 }
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500428 if (!PERIPHERAL_BITBAND(GPIOC_PDIR, 7)) {
Brian Silverman6260c092018-01-14 15:21:36 -0800429 buttons |= 0x4;
430 }
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500431 if (!PERIPHERAL_BITBAND(GPIOD_PDIR, 0)) {
Brian Silverman6260c092018-01-14 15:21:36 -0800432 buttons |= 0x8;
433 }
434
435 float trigger_angle = absolute_trigger_angle;
436
437 // Adjust the trigger range for reporting back.
438 // TODO(austin): We'll likely need to make this symmetric for the controls to
439 // work out well.
440 if (trigger_angle > kTriggerCenter) {
441 trigger_angle = (trigger_angle - kTriggerCenter) / (1.0f - kTriggerCenter);
442 } else {
443 trigger_angle = (trigger_angle - kTriggerCenter) /
444 (kTriggerCenter - kTriggerMaxExtension);
445 }
446
447 // TODO(austin): Class + fns. This is a mess.
448 // TODO(austin): Move this to a separate file. It's too big.
449 int can_trigger = ConvertFloat16(absolute_trigger_angle);
450 int can_trigger_velocity =
451 ConvertFloat16(trigger_observer->X_hat()(1, 0) / 50.0f);
452 int can_trigger_torque =
453 ConvertFloat16(trigger_observer->X_hat()(2, 0) * 2.0f);
454 int can_trigger_current = ConvertFloat14(trigger_goal_current / 10.0f);
455
456 int can_wheel = ConvertFloat16(absolute_wheel_angle);
457 int can_wheel_velocity =
458 ConvertFloat16(wheel_observer->X_hat()(1, 0) / 50.0f);
459 int can_wheel_torque = ConvertFloat16(wheel_observer->X_hat()(2, 0) * 2.0f);
460 int can_wheel_current = ConvertFloat14(wheel_goal_current / 10.0f);
461
462 {
463 const uint8_t trigger_joystick_values[8] = {
464 static_cast<uint8_t>(can_trigger & 0xff),
465 static_cast<uint8_t>((can_trigger >> 8) & 0xff),
466 static_cast<uint8_t>(can_trigger_velocity & 0xff),
467 static_cast<uint8_t>((can_trigger_velocity >> 8) & 0xff),
468 static_cast<uint8_t>(can_trigger_torque & 0xff),
469 static_cast<uint8_t>((can_trigger_torque >> 8) & 0xff),
470 static_cast<uint8_t>(can_trigger_current & 0xff),
471 static_cast<uint8_t>(((buttons & 0x3) << 6) |
472 (can_trigger_current >> 8))};
473 const uint8_t wheel_joystick_values[8] = {
474 static_cast<uint8_t>(can_wheel & 0xff),
475 static_cast<uint8_t>((can_wheel >> 8) & 0xff),
476 static_cast<uint8_t>(can_wheel_velocity & 0xff),
477 static_cast<uint8_t>((can_wheel_velocity >> 8) & 0xff),
478 static_cast<uint8_t>(can_wheel_torque & 0xff),
479 static_cast<uint8_t>((can_wheel_torque >> 8) & 0xff),
480 static_cast<uint8_t>(can_wheel_current & 0xff),
481 static_cast<uint8_t>(((buttons & 0xc) << 4) |
482 (can_wheel_current >> 8))};
483
484 can_send(0, trigger_joystick_values, 8, 2);
485 can_send(1, wheel_joystick_values, 8, 3);
486 }
487
488 ::Eigen::Matrix<float, 1, 1> trigger_U;
489 trigger_U << trigger_goal_current;
490 ::Eigen::Matrix<float, 1, 1> wheel_U;
491 wheel_U << wheel_goal_current;
492 trigger_observer->Predict(trigger_plant, trigger_U,
493 ::std::chrono::milliseconds(1));
494 wheel_observer->Predict(wheel_plant, wheel_U, ::std::chrono::milliseconds(1));
495}
496
497void ConfigurePwmFtm(BigFTM *pwm_ftm) {
498 // Put them all into combine active-high mode, and all the low ones staying
499 // off all the time by default. We'll then use only the low ones.
500 pwm_ftm->C0SC = FTM_CSC_ELSB;
501 pwm_ftm->C0V = 0;
502 pwm_ftm->C1SC = FTM_CSC_ELSB;
503 pwm_ftm->C1V = 0;
504 pwm_ftm->C2SC = FTM_CSC_ELSB;
505 pwm_ftm->C2V = 0;
506 pwm_ftm->C3SC = FTM_CSC_ELSB;
507 pwm_ftm->C3V = 0;
508 pwm_ftm->C4SC = FTM_CSC_ELSB;
509 pwm_ftm->C4V = 0;
510 pwm_ftm->C5SC = FTM_CSC_ELSB;
511 pwm_ftm->C5V = 0;
512 pwm_ftm->C6SC = FTM_CSC_ELSB;
513 pwm_ftm->C6V = 0;
514 pwm_ftm->C7SC = FTM_CSC_ELSB;
515 pwm_ftm->C7V = 0;
516
517 pwm_ftm->COMBINE = FTM_COMBINE_SYNCEN3 /* Synchronize updates usefully */ |
518 FTM_COMBINE_COMP3 /* Make them complementary */ |
519 FTM_COMBINE_COMBINE3 /* Combine the channels */ |
520 FTM_COMBINE_SYNCEN2 /* Synchronize updates usefully */ |
521 FTM_COMBINE_COMP2 /* Make them complementary */ |
522 FTM_COMBINE_COMBINE2 /* Combine the channels */ |
523 FTM_COMBINE_SYNCEN1 /* Synchronize updates usefully */ |
524 FTM_COMBINE_COMP1 /* Make them complementary */ |
525 FTM_COMBINE_COMBINE1 /* Combine the channels */ |
526 FTM_COMBINE_SYNCEN0 /* Synchronize updates usefully */ |
527 FTM_COMBINE_COMP0 /* Make them complementary */ |
528 FTM_COMBINE_COMBINE0 /* Combine the channels */;
529}
530
531bool CountValid(uint32_t count) {
532 static constexpr int kMaxMovement = 1;
533 return count <= kMaxMovement || count >= (4096 - kMaxMovement);
534}
535
536bool ZeroMotors(uint16_t *motor0_offset, uint16_t *motor1_offset,
537 uint16_t *wheel_offset) {
538 static constexpr int kNumberSamples = 1024;
539 static_assert(UINT16_MAX * kNumberSamples <= UINT32_MAX, "Too many samples");
540 uint32_t motor0_sum = 0, motor1_sum = 0, wheel_sum = 0;
541
542 // First clear both encoders.
543 MOTOR0_ENCODER_FTM->CNT = MOTOR1_ENCODER_FTM->CNT = 0;
544 for (int i = 0; i < kNumberSamples; ++i) {
545 delay(1);
546
547 if (!CountValid(MOTOR0_ENCODER_FTM->CNT)) {
548 printf("Motor 0 moved too much\n");
549 return false;
550 }
551 if (!CountValid(MOTOR1_ENCODER_FTM->CNT)) {
552 printf("Motor 1 moved too much\n");
553 return false;
554 }
555
556 DisableInterrupts disable_interrupts;
557 const SmallInitReadings readings = AdcReadSmallInit(disable_interrupts);
558 motor0_sum += readings.motor0_abs;
559 motor1_sum += readings.motor1_abs;
560 wheel_sum += readings.wheel_abs;
561 }
562
563 *motor0_offset = (motor0_sum + kNumberSamples / 2) / kNumberSamples;
564 *motor1_offset = (motor1_sum + kNumberSamples / 2) / kNumberSamples;
565 *wheel_offset = (wheel_sum + kNumberSamples / 2) / kNumberSamples;
566
567 return true;
568}
569
570} // namespace
571
572extern "C" int main() {
573 // for background about this startup delay, please see these conversations
574 // https://forum.pjrc.com/threads/36606-startup-time-(400ms)?p=113980&viewfull=1#post113980
575 // https://forum.pjrc.com/threads/31290-Teensey-3-2-Teensey-Loader-1-24-Issues?p=87273&viewfull=1#post87273
576 delay(400);
577
578 // Set all interrupts to the second-lowest priority to start with.
579 for (int i = 0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_SANE_PRIORITY(i, 0xD);
580
581 // Now set priorities for all the ones we care about. They only have meaning
582 // relative to each other, which means centralizing them here makes it a lot
583 // more manageable.
584 NVIC_SET_SANE_PRIORITY(IRQ_USBOTG, 0x7);
585 NVIC_SET_SANE_PRIORITY(IRQ_FTM0, 0x3);
586 NVIC_SET_SANE_PRIORITY(IRQ_FTM3, 0x3);
587 NVIC_SET_SANE_PRIORITY(IRQ_PIT_CH3, 0x5);
588
589 // Set the LED's pin to output mode.
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500590 PERIPHERAL_BITBAND(GPIOC_PDDR, 5) = 1;
Brian Silverman6260c092018-01-14 15:21:36 -0800591 PORTC_PCR5 = PORT_PCR_DSE | PORT_PCR_MUX(1);
592
593 // Set up the CAN pins.
594 PORTA_PCR12 = PORT_PCR_DSE | PORT_PCR_MUX(2);
595 PORTA_PCR13 = PORT_PCR_DSE | PORT_PCR_MUX(2);
596
Brian Silvermanff7b3872018-03-10 18:08:30 -0800597 // .1ms filter time.
598 PORTA_DFWR = PORTC_DFWR = PORTD_DFWR = PORTE_DFWR = 6000;
599
Brian Silverman6260c092018-01-14 15:21:36 -0800600 // BTN0
601 PORTC_PCR7 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
Brian Silvermanff7b3872018-03-10 18:08:30 -0800602 PORTC_DFER |= 1 << 7;
Brian Silverman6260c092018-01-14 15:21:36 -0800603 // BTN1
604 PORTE_PCR26 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
Brian Silvermanff7b3872018-03-10 18:08:30 -0800605 PORTE_DFER |= 1 << 26;
Brian Silverman6260c092018-01-14 15:21:36 -0800606 // BTN2
607 PORTA_PCR14 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
Brian Silvermanff7b3872018-03-10 18:08:30 -0800608 PORTA_DFER |= 1 << 14;
Brian Silverman6260c092018-01-14 15:21:36 -0800609 // BTN3
610 PORTD_PCR0 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
Brian Silvermanff7b3872018-03-10 18:08:30 -0800611 PORTD_DFER |= 1 << 0;
612 // BTN4
613 PORTD_PCR7 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
614 PORTD_DFER |= 1 << 7;
615 // BTN5 (only new revision)
616 PORTA_PCR15 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
617 PORTA_DFER |= 1 << 15;
Brian Silverman6260c092018-01-14 15:21:36 -0800618
619 PORTA_PCR5 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
620
621 DMA_CR = DMA_CR_EMLM;
622
623 teensy::UsbDevice usb_device(0, 0x16c0, 0x0490);
624 usb_device.SetManufacturer("FRC 971 Spartan Robotics");
625 usb_device.SetProduct("Pistol Grip Controller debug");
626 teensy::AcmTty tty1(&usb_device);
627 teensy::AcmTty tty2(&usb_device);
628 global_stdout.store(&tty1, ::std::memory_order_release);
629 usb_device.Initialize();
630
631 AdcInitSmall();
632 MathInit();
633 delay(100);
634 can_init(2, 3);
635
636 GPIOD_PCOR = 1 << 3;
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500637 PERIPHERAL_BITBAND(GPIOD_PDDR, 3) = 1;
Brian Silverman6260c092018-01-14 15:21:36 -0800638 PORTD_PCR3 = PORT_PCR_DSE | PORT_PCR_MUX(1);
639 GPIOD_PSOR = 1 << 3;
640
641 GPIOC_PCOR = 1 << 4;
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500642 PERIPHERAL_BITBAND(GPIOC_PDDR, 4) = 1;
Brian Silverman6260c092018-01-14 15:21:36 -0800643 PORTC_PCR4 = PORT_PCR_DSE | PORT_PCR_MUX(1);
644 GPIOC_PSOR = 1 << 4;
645
646 LittleMotorControlsImplementation controls0, controls1;
647
648 delay(100);
649
650 // M0_EA = FTM1_QD_PHB
651 PORTB_PCR19 = PORT_PCR_MUX(6);
652 // M0_EB = FTM1_QD_PHA
653 PORTB_PCR18 = PORT_PCR_MUX(6);
654
655 // M1_EA = FTM1_QD_PHA
656 PORTB_PCR0 = PORT_PCR_MUX(6);
657 // M1_EB = FTM1_QD_PHB
658 PORTB_PCR1 = PORT_PCR_MUX(6);
659
660 // M0_CH0 = FTM3_CH4
661 PORTC_PCR8 = PORT_PCR_DSE | PORT_PCR_MUX(3);
662 // M0_CH1 = FTM3_CH2
663 PORTD_PCR2 = PORT_PCR_DSE | PORT_PCR_MUX(4);
664 // M0_CH2 = FTM3_CH6
665 PORTC_PCR10 = PORT_PCR_DSE | PORT_PCR_MUX(3);
666
667 // M1_CH0 = FTM0_CH0
668 PORTC_PCR1 = PORT_PCR_DSE | PORT_PCR_MUX(4);
669 // M1_CH1 = FTM0_CH2
670 PORTC_PCR3 = PORT_PCR_DSE | PORT_PCR_MUX(4);
671 // M1_CH2 = FTM0_CH4
672 PORTD_PCR4 = PORT_PCR_DSE | PORT_PCR_MUX(4);
673
674 Motor motor0(
675 MOTOR0_PWM_FTM, MOTOR0_ENCODER_FTM, &controls0,
676 {&MOTOR0_PWM_FTM->C4V, &MOTOR0_PWM_FTM->C2V, &MOTOR0_PWM_FTM->C6V});
677 motor0.set_debug_tty(&tty2);
678 motor0.set_switching_divisor(kSwitchingDivisor);
679 Motor motor1(
680 MOTOR1_PWM_FTM, MOTOR1_ENCODER_FTM, &controls1,
681 {&MOTOR1_PWM_FTM->C0V, &MOTOR1_PWM_FTM->C2V, &MOTOR1_PWM_FTM->C4V});
682 motor1.set_debug_tty(&tty2);
683 motor1.set_switching_divisor(kSwitchingDivisor);
684 ConfigurePwmFtm(MOTOR0_PWM_FTM);
685 ConfigurePwmFtm(MOTOR1_PWM_FTM);
686 motor0.Init();
687 motor1.Init();
688 global_motor0.store(&motor0, ::std::memory_order_relaxed);
689 global_motor1.store(&motor1, ::std::memory_order_relaxed);
690
691 SIM_SCGC6 |= SIM_SCGC6_PIT;
Brian Silvermanb0de2402018-03-24 03:48:28 -0400692 // Workaround for errata e7914.
693 (void)PIT_MCR;
Brian Silverman6260c092018-01-14 15:21:36 -0800694 PIT_MCR = 0;
Brian Silvermanb0de2402018-03-24 03:48:28 -0400695 PIT_LDVAL3 = (BUS_CLOCK_FREQUENCY / 1000) - 1;
Brian Silverman6260c092018-01-14 15:21:36 -0800696 PIT_TCTRL3 = PIT_TCTRL_TIE | PIT_TCTRL_TEN;
697
698 // Have them both wait for the GTB signal.
699 FTM0->CONF = FTM3->CONF =
700 FTM_CONF_GTBEEN | FTM_CONF_NUMTOF(kSwitchingDivisor - 1);
701 // Make FTM3's period half of what it should be so we can get it a half-cycle
702 // out of phase.
703 const uint32_t original_mod = FTM3->MOD;
704 FTM3->MOD = ((original_mod + 1) / 2) - 1;
705 FTM3->SYNC |= FTM_SYNC_SWSYNC;
706
707 // Output triggers to things like the PDBs on initialization.
708 FTM0_EXTTRIG = FTM_EXTTRIG_INITTRIGEN;
709 FTM3_EXTTRIG = FTM_EXTTRIG_INITTRIGEN;
710 // Don't let any memory accesses sneak past here, because we actually
711 // need everything to be starting up.
712 __asm__("" ::: "memory");
713
714 // Give everything a chance to get going.
715 delay(100);
716
717 printf("BSS: %p-%p\n", __bss_ram_start__, __bss_ram_end__);
718 printf("data: %p-%p\n", __data_ram_start__, __data_ram_end__);
719 printf("heap start: %p\n", __heap_start__);
720 printf("stack start: %p\n", __stack_end__);
721
722 printf("Zeroing motors\n");
723 uint16_t motor0_offset, motor1_offset, wheel_offset;
724 while (!ZeroMotors(&motor0_offset, &motor1_offset, &wheel_offset)) {
725 }
726 printf("Done zeroing\n");
727
728 const float motor0_offset_scaled = -analog_ratio(motor0_offset);
729 const float motor1_offset_scaled = analog_ratio(motor1_offset);
730 // Good for the initial trigger.
731 {
732 constexpr float kZeroOffset0 = 0.27f;
733 const int motor0_starting_point = static_cast<int>(
734 (motor0_offset_scaled + (kZeroOffset0 / 7.0f)) * 4096.0f);
735 printf("Motor 0 starting at %d\n", motor0_starting_point);
736 motor0.set_encoder_calibration_offset(motor0_starting_point);
737 motor0.set_encoder_multiplier(-1);
738
739 // Calibrate neutral here.
740 motor0.set_encoder_offset(motor0.encoder_offset() - 2065 + 20);
741
742 uint32_t new_encoder = motor0.wrapped_encoder();
743 int32_t absolute_encoder = motor0.absolute_encoder(new_encoder);
744 printf("Motor 0 encoder %d absolute %d\n", static_cast<int>(new_encoder),
745 static_cast<int>(absolute_encoder));
746 }
747
748 {
749 constexpr float kZeroOffset1 = 0.26f;
750 const int motor1_starting_point = static_cast<int>(
751 (motor1_offset_scaled + (kZeroOffset1 / 7.0f)) * 4096.0f);
752 printf("Motor 1 starting at %d\n", motor1_starting_point);
753 motor1.set_encoder_calibration_offset(motor1_starting_point);
754 motor1.set_encoder_multiplier(-1);
755
756 float wheel_position = absolute_wheel(analog_ratio(wheel_offset));
757
758 uint32_t encoder = motor1.wrapped_encoder();
759
760 printf("Wheel starting at %d, encoder %" PRId32 "\n",
761 static_cast<int>(wheel_position * 1000.0f), encoder);
762
763 constexpr float kWheelGearRatio = (1.25f + 0.02f) / 0.35f;
764 constexpr float kWrappedWheelAtZero = 0.6586310546875f;
765
766 const int encoder_wraps =
767 static_cast<int>(lround(wheel_position * kWheelGearRatio -
768 (encoder / 4096.f) + kWrappedWheelAtZero));
769
770 printf("Wraps: %d\n", encoder_wraps);
771 motor1.set_encoder_offset(4096 * encoder_wraps + motor1.encoder_offset() -
772 static_cast<int>(kWrappedWheelAtZero * 4096));
773 printf("Wheel encoder now at %d\n",
774 static_cast<int>(1000.f / 4096.f *
775 motor1.absolute_encoder(motor1.wrapped_encoder())));
776 }
777
778 // Turn an LED on for Austin.
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500779 PERIPHERAL_BITBAND(GPIOC_PDDR, 6) = 1;
Brian Silverman6260c092018-01-14 15:21:36 -0800780 GPIOC_PCOR = 1 << 6;
781 PORTC_PCR6 = PORT_PCR_DSE | PORT_PCR_MUX(1);
782
783 // M0_THW
784 PORTC_PCR11 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
785 // M0_FAULT
786 PORTD_PCR6 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
787 // M1_THW
788 PORTC_PCR2 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
789 // M1_FAULT
790 PORTD_PCR5 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_MUX(1);
791
792 motor0.Start();
793 motor1.Start();
794 {
795 // We rely on various things happening faster than the timer period, so make
796 // sure slow USB or whatever interrupts don't prevent that.
797 DisableInterrupts disable_interrupts;
798
799 // First clear the overflow flag.
800 FTM3->SC &= ~FTM_SC_TOF;
801
802 // Now poke the GTB to actually start both timers.
803 FTM0->CONF = FTM_CONF_GTBEEN | FTM_CONF_GTBEOUT |
804 FTM_CONF_NUMTOF(kSwitchingDivisor - 1);
805
806 // Wait for it to overflow twice. For some reason, just once doesn't work.
807 while (!(FTM3->SC & FTM_SC_TOF)) {
808 }
809 FTM3->SC &= ~FTM_SC_TOF;
810 while (!(FTM3->SC & FTM_SC_TOF)) {
811 }
812
813 // Now put the MOD value back to what it was.
814 FTM3->MOD = original_mod;
815 FTM3->PWMLOAD = FTM_PWMLOAD_LDOK;
816
817 // And then clear the overflow flags before enabling interrupts so we
818 // actually wait until the next overflow to start doing interrupts.
819 FTM0->SC &= ~FTM_SC_TOF;
820 FTM3->SC &= ~FTM_SC_TOF;
821 NVIC_ENABLE_IRQ(IRQ_FTM0);
822 NVIC_ENABLE_IRQ(IRQ_FTM3);
823 }
824 global_trigger_plant.store(
825 new StateFeedbackPlant<3, 1, 1, float>(MakeIntegralHapticTriggerPlant()));
826 global_trigger_observer.store(new StateFeedbackObserver<3, 1, 1, float>(
827 MakeIntegralHapticTriggerObserver()));
828 global_trigger_observer.load(::std::memory_order_relaxed)
829 ->Reset(global_trigger_plant.load(::std::memory_order_relaxed));
830
831 global_wheel_plant.store(
832 new StateFeedbackPlant<3, 1, 1, float>(MakeIntegralHapticWheelPlant()));
833 global_wheel_observer.store(new StateFeedbackObserver<3, 1, 1, float>(
834 MakeIntegralHapticWheelObserver()));
835 global_wheel_observer.load(::std::memory_order_relaxed)
836 ->Reset(global_wheel_plant.load(::std::memory_order_relaxed));
837
838 delay(1000);
839
840 NVIC_ENABLE_IRQ(IRQ_PIT_CH3);
841
842 // TODO(Brian): Use SLEEPONEXIT to reduce interrupt latency?
843 while (true) {
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500844 if (!PERIPHERAL_BITBAND(GPIOC_PDIR, 11)) {
845 if (!PERIPHERAL_BITBAND(GPIOC_PDOR, 5)) {
Brian Silverman6260c092018-01-14 15:21:36 -0800846 printf("M0_THW\n");
847 }
848 GPIOC_PSOR = 1 << 5;
849 }
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500850 if (!PERIPHERAL_BITBAND(GPIOD_PDIR, 6)) {
851 if (!PERIPHERAL_BITBAND(GPIOC_PDOR, 5)) {
Brian Silverman6260c092018-01-14 15:21:36 -0800852 printf("M0_FAULT\n");
853 }
854 GPIOC_PSOR = 1 << 5;
855 }
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500856 if (!PERIPHERAL_BITBAND(GPIOC_PDIR, 2)) {
857 if (!PERIPHERAL_BITBAND(GPIOC_PDOR, 5)) {
Brian Silverman6260c092018-01-14 15:21:36 -0800858 printf("M1_THW\n");
859 }
860 GPIOC_PSOR = 1 << 5;
861 }
Brian Silverman33eb5fa2018-02-11 18:36:19 -0500862 if (!PERIPHERAL_BITBAND(GPIOD_PDIR, 5)) {
863 if (!PERIPHERAL_BITBAND(GPIOC_PDOR, 5)) {
Brian Silverman6260c092018-01-14 15:21:36 -0800864 printf("M1_FAULT\n");
865 }
866 GPIOC_PSOR = 1 << 5;
867 }
868 }
869
870 return 0;
871}
872
873} // namespace salsa
874} // namespace frc971