blob: 0470c31d5531bc5b66604f751eefa7d495b66e2f [file] [log] [blame]
Brian Silverman54dd2fe2018-03-16 23:44:31 -07001// This file has the main for the Teensy on the simple receiver board.
2
3#include <inttypes.h>
4#include <stdio.h>
5#include <atomic>
Austin Schuhbb735b72019-01-03 12:58:41 -08006#include <chrono>
Brian Silverman54dd2fe2018-03-16 23:44:31 -07007#include <cmath>
8
Austin Schuh4fae0fc2018-03-27 23:51:42 -07009#include "frc971/control_loops/drivetrain/polydrivetrain.h"
Brian Silverman54dd2fe2018-03-16 23:44:31 -070010#include "motors/core/kinetis.h"
Brian Silvermana3a172b2018-03-24 03:53:32 -040011#include "motors/core/time.h"
Brian Silverman54dd2fe2018-03-16 23:44:31 -070012#include "motors/peripheral/adc.h"
13#include "motors/peripheral/can.h"
Brian Silvermana3a172b2018-03-24 03:53:32 -040014#include "motors/peripheral/configuration.h"
Brian Silverman4787a6e2018-10-06 16:00:54 -070015#include "motors/print/print.h"
Austin Schuh4fae0fc2018-03-27 23:51:42 -070016#include "motors/seems_reasonable/drivetrain_dog_motor_plant.h"
17#include "motors/seems_reasonable/polydrivetrain_dog_motor_plant.h"
18#include "motors/seems_reasonable/spring.h"
Brian Silverman54dd2fe2018-03-16 23:44:31 -070019#include "motors/util.h"
20
21namespace frc971 {
22namespace motors {
23namespace {
24
Austin Schuhbcce26a2018-03-26 23:41:24 -070025using ::frc971::control_loops::drivetrain::DrivetrainConfig;
26using ::frc971::control_loops::drivetrain::PolyDrivetrain;
27using ::frc971::constants::ShifterHallEffect;
28using ::frc971::control_loops::DrivetrainQueue_Goal;
29using ::frc971::control_loops::DrivetrainQueue_Output;
Austin Schuh4fae0fc2018-03-27 23:51:42 -070030using ::motors::seems_reasonable::Spring;
Austin Schuhbcce26a2018-03-26 23:41:24 -070031
Austin Schuhbb735b72019-01-03 12:58:41 -080032namespace chrono = ::std::chrono;
33
Brian Silverman9ed2cf12018-05-12 13:06:38 -070034struct SimpleAdcReadings {
35 uint16_t sin, cos;
36};
37
38void AdcInitSimple() {
39 AdcInitCommon();
40
41 // ENC_SIN ADC0_SE23
42 // ENC_COS ADC1_SE23
43}
44
45SimpleAdcReadings AdcReadSimple(const DisableInterrupts &) {
46 SimpleAdcReadings r;
47
48 ADC0_SC1A = 23;
49 ADC1_SC1A = 23;
50 while (!(ADC0_SC1A & ADC_SC1_COCO)) {
51 }
52 while (!(ADC1_SC1A & ADC_SC1_COCO)) {
53 }
54 r.sin = ADC0_RA;
55 r.cos = ADC1_RA;
56
57 return r;
58}
59
Austin Schuhbcce26a2018-03-26 23:41:24 -070060const ShifterHallEffect kThreeStateDriveShifter{0.0, 0.0, 0.25, 0.75};
61
62const DrivetrainConfig<float> &GetDrivetrainConfig() {
63 static DrivetrainConfig<float> kDrivetrainConfig{
64 ::frc971::control_loops::drivetrain::ShifterType::NO_SHIFTER,
65 ::frc971::control_loops::drivetrain::LoopType::OPEN_LOOP,
66 ::frc971::control_loops::drivetrain::GyroType::SPARTAN_GYRO,
67 ::frc971::control_loops::drivetrain::IMUType::IMU_X,
68
69 ::motors::seems_reasonable::MakeDrivetrainLoop,
70 ::motors::seems_reasonable::MakeVelocityDrivetrainLoop,
71 ::std::function<StateFeedbackLoop<7, 2, 4, float>()>(),
72
Austin Schuhbb735b72019-01-03 12:58:41 -080073 chrono::duration_cast<chrono::nanoseconds>(
74 chrono::duration<float>(::motors::seems_reasonable::kDt)),
75 ::motors::seems_reasonable::kRobotRadius,
Austin Schuhbcce26a2018-03-26 23:41:24 -070076 ::motors::seems_reasonable::kWheelRadius, ::motors::seems_reasonable::kV,
77
78 ::motors::seems_reasonable::kHighGearRatio,
Austin Schuhe6a9fdf2019-01-12 16:05:43 -080079 ::motors::seems_reasonable::kLowGearRatio,
80 ::motors::seems_reasonable::kJ,
81 ::motors::seems_reasonable::kMass,
82 kThreeStateDriveShifter,
Austin Schuhbcce26a2018-03-26 23:41:24 -070083 kThreeStateDriveShifter, true /* default_high_gear */,
84 0 /* down_offset if using constants use
85 constants::GetValues().down_error */, 0.8 /* wheel_non_linearity */,
86 1.2 /* quickturn_wheel_multiplier */, 1.5 /* wheel_multiplier */,
87 };
88
89 return kDrivetrainConfig;
90};
91
92
Austin Schuhbcce26a2018-03-26 23:41:24 -070093::std::atomic<PolyDrivetrain<float> *> global_polydrivetrain{nullptr};
Austin Schuh4fae0fc2018-03-27 23:51:42 -070094::std::atomic<Spring *> global_spring{nullptr};
Austin Schuhbcce26a2018-03-26 23:41:24 -070095
Brian Silvermana3a172b2018-03-24 03:53:32 -040096// Last width we received on each channel.
Brian Silverman7f5f1442018-04-06 13:00:50 -040097uint16_t pwm_input_widths[6];
Brian Silvermana3a172b2018-03-24 03:53:32 -040098// When we received a pulse on each channel in milliseconds.
Brian Silverman7f5f1442018-04-06 13:00:50 -040099uint32_t pwm_input_times[6];
Brian Silvermana3a172b2018-03-24 03:53:32 -0400100
Austin Schuhbcce26a2018-03-26 23:41:24 -0700101constexpr int kChannelTimeout = 100;
102
103bool lost_channel(int channel) {
104 DisableInterrupts disable_interrupts;
105 if (time_after(millis(),
106 time_add(pwm_input_times[channel], kChannelTimeout))) {
107 return true;
108 }
109 return false;
110}
111
Brian Silvermana3a172b2018-03-24 03:53:32 -0400112// Returns the most recently captured value for the specified input channel
113// scaled from -1 to 1, or 0 if it was captured over 100ms ago.
114float convert_input_width(int channel) {
115 uint16_t width;
116 {
117 DisableInterrupts disable_interrupts;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700118 if (time_after(millis(),
119 time_add(pwm_input_times[channel], kChannelTimeout))) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400120 return 0;
121 }
122
123 width = pwm_input_widths[channel];
124 }
125
126 // Values measured with a channel mapped to a button.
127 static constexpr uint16_t kMinWidth = 4133;
128 static constexpr uint16_t kMaxWidth = 7177;
129 if (width < kMinWidth) {
130 width = kMinWidth;
131 } else if (width > kMaxWidth) {
132 width = kMaxWidth;
133 }
134 return (static_cast<float>(2 * (width - kMinWidth)) /
135 static_cast<float>(kMaxWidth - kMinWidth)) -
136 1.0f;
137}
138
139// Sends a SET_RPM command to the specified VESC.
140// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
141// bandwidth.
142void vesc_set_rpm(int vesc_id, float rpm) {
143 const int32_t rpm_int = rpm;
144 uint32_t id = CAN_EFF_FLAG;
145 id |= vesc_id;
146 id |= (0x03 /* SET_RPM */) << 8;
147 uint8_t data[4] = {
148 static_cast<uint8_t>((rpm_int >> 24) & 0xFF),
149 static_cast<uint8_t>((rpm_int >> 16) & 0xFF),
150 static_cast<uint8_t>((rpm_int >> 8) & 0xFF),
151 static_cast<uint8_t>((rpm_int >> 0) & 0xFF),
152 };
153 can_send(id, data, sizeof(data), 2 + vesc_id);
154}
155
156// Sends a SET_CURRENT command to the specified VESC.
157// current is in amps.
158// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
159// bandwidth.
160void vesc_set_current(int vesc_id, float current) {
Austin Schuhbcce26a2018-03-26 23:41:24 -0700161 constexpr float kMaxCurrent = 80.0f;
162 const int32_t current_int =
163 ::std::max(-kMaxCurrent, ::std::min(kMaxCurrent, current)) * 1000.0f;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400164 uint32_t id = CAN_EFF_FLAG;
165 id |= vesc_id;
166 id |= (0x01 /* SET_CURRENT */) << 8;
167 uint8_t data[4] = {
168 static_cast<uint8_t>((current_int >> 24) & 0xFF),
169 static_cast<uint8_t>((current_int >> 16) & 0xFF),
170 static_cast<uint8_t>((current_int >> 8) & 0xFF),
171 static_cast<uint8_t>((current_int >> 0) & 0xFF),
172 };
173 can_send(id, data, sizeof(data), 2 + vesc_id);
174}
175
Brian Silverman4d1e5272018-03-26 03:18:42 -0400176// Sends a SET_DUTY command to the specified VESC.
177// duty is from -1 to 1.
178// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
179// bandwidth.
180void vesc_set_duty(int vesc_id, float duty) {
Austin Schuhbcce26a2018-03-26 23:41:24 -0700181 constexpr int32_t kMaxDuty = 99999;
182 const int32_t duty_int = ::std::max(
183 -kMaxDuty, ::std::min(kMaxDuty, static_cast<int32_t>(duty * 100000.0f)));
Brian Silverman4d1e5272018-03-26 03:18:42 -0400184 uint32_t id = CAN_EFF_FLAG;
185 id |= vesc_id;
186 id |= (0x00 /* SET_DUTY */) << 8;
187 uint8_t data[4] = {
188 static_cast<uint8_t>((duty_int >> 24) & 0xFF),
189 static_cast<uint8_t>((duty_int >> 16) & 0xFF),
190 static_cast<uint8_t>((duty_int >> 8) & 0xFF),
191 static_cast<uint8_t>((duty_int >> 0) & 0xFF),
192 };
193 can_send(id, data, sizeof(data), 2 + vesc_id);
194}
195
Brian Silverman6c8b88b2018-09-03 18:17:02 -0700196// TODO(Brian): Move these two test functions somewhere else.
197__attribute__((unused)) void DoVescTest() {
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700198 uint32_t time = micros();
199 while (true) {
200 for (int i = 0; i < 6; ++i) {
201 const uint32_t end = time_add(time, 500000);
202 while (true) {
203 const bool done = time_after(micros(), end);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700204 float current;
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700205 if (done) {
206 current = -6;
207 } else {
208 current = 6;
209 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400210 vesc_set_current(i, current);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700211 if (done) {
212 break;
213 }
214 delay(5);
215 }
216 time = end;
217 }
218 }
219}
220
Brian Silverman6c8b88b2018-09-03 18:17:02 -0700221__attribute__((unused)) void DoReceiverTest2() {
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700222 static constexpr float kMaxRpm = 10000.0f;
223 while (true) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400224 const bool flip = convert_input_width(2) > 0;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700225
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700226 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400227 const float value = convert_input_width(0);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700228
229 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400230 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700231 if (flip) {
232 rpm *= -1.0f;
233 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400234 vesc_set_rpm(0, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700235 }
236
237 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400238 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700239 if (flip) {
240 rpm *= -1.0f;
241 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400242 vesc_set_rpm(1, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700243 }
244 }
245
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700246 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400247 const float value = convert_input_width(1);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700248
249 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400250 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700251 if (flip) {
252 rpm *= -1.0f;
253 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400254 vesc_set_rpm(2, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700255 }
256
257 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400258 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700259 if (flip) {
260 rpm *= -1.0f;
261 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400262 vesc_set_rpm(3, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700263 }
264 }
265
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700266 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400267 const float value = convert_input_width(4);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700268
269 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400270 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700271 if (flip) {
272 rpm *= -1.0f;
273 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400274 vesc_set_rpm(4, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700275 }
276
277 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400278 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700279 if (flip) {
280 rpm *= -1.0f;
281 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400282 vesc_set_rpm(5, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700283 }
284 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400285 // Give the CAN frames a chance to go out.
286 delay(5);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700287 }
288}
289
290void SetupPwmFtm(BigFTM *ftm) {
291 ftm->MODE = FTM_MODE_WPDIS;
292 ftm->MODE = FTM_MODE_WPDIS | FTM_MODE_FTMEN;
293 ftm->SC = FTM_SC_CLKS(0) /* Disable counting for now */;
294
295 // Can't change MOD according to the reference manual ("The Dual Edge Capture
296 // mode must be used with ... the FTM counter in Free running counter.").
297 ftm->MOD = 0xFFFF;
298
299 // Capturing rising edge.
300 ftm->C0SC = FTM_CSC_MSA | FTM_CSC_ELSA;
301 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400302 ftm->C1SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700303
304 // Capturing rising edge.
305 ftm->C2SC = FTM_CSC_MSA | FTM_CSC_ELSA;
306 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400307 ftm->C3SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700308
309 // Capturing rising edge.
310 ftm->C4SC = FTM_CSC_MSA | FTM_CSC_ELSA;
311 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400312 ftm->C5SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700313
314 // Capturing rising edge.
315 ftm->C6SC = FTM_CSC_MSA | FTM_CSC_ELSA;
316 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400317 ftm->C7SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700318
Brian Silvermana3a172b2018-03-24 03:53:32 -0400319 (void)ftm->STATUS;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700320 ftm->STATUS = 0x00;
321
322 ftm->COMBINE = FTM_COMBINE_DECAP3 | FTM_COMBINE_DECAPEN3 |
323 FTM_COMBINE_DECAP2 | FTM_COMBINE_DECAPEN2 |
324 FTM_COMBINE_DECAP1 | FTM_COMBINE_DECAPEN1 |
325 FTM_COMBINE_DECAP0 | FTM_COMBINE_DECAPEN0;
326
327 // 34.95ms max period before it starts wrapping and being weird.
328 ftm->SC = FTM_SC_CLKS(1) /* Use the system clock */ |
329 FTM_SC_PS(4) /* Prescaler=32 */;
330
331 ftm->MODE &= ~FTM_MODE_WPDIS;
332}
333
Brian Silverman2de95d62018-03-31 12:32:24 -0700334struct AccelerometerResult {
335 uint16_t result;
336 bool success;
337};
338
339// Does a transfer on the accelerometer. Returns the resulting frame, or a
340// failure if it takes until after end_micros.
341AccelerometerResult AccelerometerTransfer(uint16_t data, uint32_t end_micros) {
342 SPI0_SR = SPI_SR_RFDF;
343 SPI0_PUSHR = SPI_PUSHR_PCS(1) | data;
344
345 while (!(SPI0_SR & SPI_SR_RFDF)) {
346 if (time_after(micros(), end_micros)) {
347 return {0, false};
348 }
349 }
350 const uint32_t popr = SPI0_POPR;
351 SPI0_SR = SPI_SR_RFDF;
352 return {static_cast<uint16_t>(popr & 0xFFFF), true};
353}
354
355constexpr uint32_t kAccelerometerTimeout = 500;
356
357bool AccelerometerWrite(uint8_t address, uint8_t data, uint32_t end_micros) {
358 const AccelerometerResult r = AccelerometerTransfer(
359 (static_cast<uint16_t>(address) << 8) | static_cast<uint16_t>(data),
360 end_micros);
361 return r.success;
362}
363
364AccelerometerResult AccelerometerRead(uint8_t address, uint32_t end_micros) {
365 AccelerometerResult r = AccelerometerTransfer(
366 (static_cast<uint16_t>(address) << 8) | UINT16_C(0x8000), end_micros);
367 r.result = r.result & UINT16_C(0xFF);
368 return r;
369}
370
371bool accelerometer_inited = false;
372
373void AccelerometerInit() {
374 accelerometer_inited = false;
375 const uint32_t end_micros = time_add(micros(), kAccelerometerTimeout);
376 {
377 const auto who_am_i = AccelerometerRead(0xF, end_micros);
378 if (!who_am_i.success) {
379 return;
380 }
381 if (who_am_i.result != 0x32) {
382 return;
383 }
384 }
385 if (!AccelerometerWrite(
386 0x20, (1 << 5) /* Normal mode */ | (1 << 3) /* 100 Hz */ |
387 (1 << 2) /* Z enabled */ | (1 << 1) /* Y enabled */ |
388 (1 << 0) /* X enabled */,
389 end_micros)) {
390 }
391 // If want to read LSB, need to enable BDU to avoid splitting reads.
392 if (!AccelerometerWrite(0x23, (0 << 6) /* Data LSB at lower address */ |
393 (3 << 4) /* 400g full scale */ |
394 (0 << 0) /* 4-wire interface */,
395 end_micros)) {
396 }
397 accelerometer_inited = true;
398}
399
400float AccelerometerConvert(uint16_t value) {
401 return static_cast<float>(400.0 / 65536.0) * static_cast<float>(value);
402}
403
404// Returns the total acceleration (in any direction) or 0 if there's an error.
405float ReadAccelerometer() {
406 if (!accelerometer_inited) {
407 AccelerometerInit();
408 return 0;
409 }
410
411 const uint32_t end_micros = time_add(micros(), kAccelerometerTimeout);
412 const auto x = AccelerometerRead(0x29, end_micros);
413 const auto y = AccelerometerRead(0x2B, end_micros);
414 const auto z = AccelerometerRead(0x2D, end_micros);
415 if (!x.success || !y.success || !z.success) {
416 accelerometer_inited = false;
417 return 0;
418 }
419
420 const float x_g = AccelerometerConvert(x.result);
421 const float y_g = AccelerometerConvert(y.result);
422 const float z_g = AccelerometerConvert(z.result);
423 return ::std::sqrt(x_g * x_g + y_g * y_g + z_g * z_g);
424}
425
Brian Silvermana3a172b2018-03-24 03:53:32 -0400426extern "C" void ftm0_isr() {
427 while (true) {
428 const uint32_t status = FTM0->STATUS;
429 if (status == 0) {
430 return;
431 }
432
433 if (status & (1 << 1)) {
434 const uint32_t start = FTM0->C0V;
435 const uint32_t end = FTM0->C1V;
436 pwm_input_widths[0] = (end - start) & 0xFFFF;
437 pwm_input_times[0] = millis();
438 }
439 if (status & (1 << 7)) {
440 const uint32_t start = FTM0->C6V;
441 const uint32_t end = FTM0->C7V;
442 pwm_input_widths[1] = (end - start) & 0xFFFF;
443 pwm_input_times[1] = millis();
444 }
445 if (status & (1 << 5)) {
446 const uint32_t start = FTM0->C4V;
447 const uint32_t end = FTM0->C5V;
448 pwm_input_widths[2] = (end - start) & 0xFFFF;
449 pwm_input_times[2] = millis();
450 }
451 if (status & (1 << 3)) {
452 const uint32_t start = FTM0->C2V;
453 const uint32_t end = FTM0->C3V;
454 pwm_input_widths[4] = (end - start) & 0xFFFF;
455 pwm_input_times[4] = millis();
456 }
457
458 FTM0->STATUS = 0;
459 }
460}
461
462extern "C" void ftm3_isr() {
463 while (true) {
464 const uint32_t status = FTM3->STATUS;
465 if (status == 0) {
466 return;
467 }
468
469 if (status & (1 << 3)) {
470 const uint32_t start = FTM3->C2V;
471 const uint32_t end = FTM3->C3V;
472 pwm_input_widths[3] = (end - start) & 0xFFFF;
473 pwm_input_times[3] = millis();
474 }
Brian Silverman7f5f1442018-04-06 13:00:50 -0400475 if (status & (1 << 7)) {
476 const uint32_t start = FTM3->C6V;
477 const uint32_t end = FTM3->C7V;
478 pwm_input_widths[5] = (end - start) & 0xFFFF;
479 pwm_input_times[5] = millis();
480 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400481
482 FTM3->STATUS = 0;
483 }
484}
485
486float ConvertEncoderChannel(uint16_t reading) {
487 // Theoretical values based on the datasheet are 931 and 2917.
488 // With these values, the magnitude ranges from 0.99-1.03, which works fine
489 // (the encoder's output appears to get less accurate in one quadrant for some
490 // reason, hence the variation).
491 static constexpr uint16_t kMin = 802, kMax = 3088;
492 if (reading < kMin) {
493 reading = kMin;
494 } else if (reading > kMax) {
495 reading = kMax;
496 }
497 return (static_cast<float>(2 * (reading - kMin)) /
498 static_cast<float>(kMax - kMin)) -
499 1.0f;
500}
501
502struct EncoderReading {
Brian Silvermana96c1a42018-05-12 12:11:31 -0700503 EncoderReading(const SimpleAdcReadings &adc_readings) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400504 const float sin = ConvertEncoderChannel(adc_readings.sin);
505 const float cos = ConvertEncoderChannel(adc_readings.cos);
506
Austin Schuhbcce26a2018-03-26 23:41:24 -0700507 const float magnitude = hypot(sin, cos);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400508 const float magnitude_error = ::std::abs(magnitude - 1.0f);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700509 valid = magnitude_error < 0.30f;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400510
511 angle = ::std::atan2(sin, cos);
512 }
513
514 // Angle in radians, in [-pi, pi].
515 float angle;
516
517 bool valid;
518};
519
520extern "C" void pit3_isr() {
521 PIT_TFLG3 = 1;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700522 PolyDrivetrain<float> *polydrivetrain =
523 global_polydrivetrain.load(::std::memory_order_acquire);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700524 Spring *spring = global_spring.load(::std::memory_order_acquire);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400525
Brian Silvermana96c1a42018-05-12 12:11:31 -0700526 SimpleAdcReadings adc_readings;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400527 {
528 DisableInterrupts disable_interrupts;
Brian Silvermana96c1a42018-05-12 12:11:31 -0700529 adc_readings = AdcReadSimple(disable_interrupts);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400530 }
531
532 EncoderReading encoder(adc_readings);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700533 static float last_good_encoder = 0.0f;
534 static int invalid_encoder_count = 0;
535 if (encoder.valid) {
536 last_good_encoder = encoder.angle;
537 invalid_encoder_count = 0;
538 } else {
539 ++invalid_encoder_count;
540 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400541
Austin Schuhe666dc62018-08-08 21:09:12 -0700542 const bool lost_spring_channel = lost_channel(2) || lost_channel(3) ||
543 lost_channel(4) || lost_channel(5) ||
544 (convert_input_width(4) < 0.5f);
545
546 const bool lost_drive_channel = lost_channel(0) || lost_channel(1) ||
547 (::std::abs(convert_input_width(4)) < 0.5f);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700548
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700549 if (polydrivetrain != nullptr && spring != nullptr) {
Austin Schuhbcce26a2018-03-26 23:41:24 -0700550 DrivetrainQueue_Goal goal;
551 goal.control_loop_driving = false;
Austin Schuhe666dc62018-08-08 21:09:12 -0700552 if (lost_drive_channel) {
Austin Schuhbcce26a2018-03-26 23:41:24 -0700553 goal.throttle = 0.0f;
554 goal.wheel = 0.0f;
555 } else {
556 goal.throttle = convert_input_width(1);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700557 goal.wheel = -convert_input_width(0);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700558 }
Austin Schuhbcce26a2018-03-26 23:41:24 -0700559 goal.quickturn = ::std::abs(polydrivetrain->velocity()) < 0.25f;
560
561 DrivetrainQueue_Output output;
562
563 polydrivetrain->SetGoal(goal);
Austin Schuheeec74a2019-01-27 20:58:59 -0800564 polydrivetrain->Update(12.0f);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700565 polydrivetrain->SetOutput(&output);
566
567 vesc_set_duty(0, -output.left_voltage / 12.0f);
568 vesc_set_duty(1, -output.left_voltage / 12.0f);
569
570 vesc_set_duty(2, output.right_voltage / 12.0f);
571 vesc_set_duty(3, output.right_voltage / 12.0f);
572
Austin Schuhe666dc62018-08-08 21:09:12 -0700573 const bool prime = convert_input_width(2) > 0.1f;
574 const bool fire = convert_input_width(3) > 0.1f;
575 const bool force_move =
576 (convert_input_width(5) > 0.1f) && !lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700577
Austin Schuhe666dc62018-08-08 21:09:12 -0700578 bool unload = lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700579 static bool was_lost = true;
Austin Schuhe666dc62018-08-08 21:09:12 -0700580 bool force_reset = !lost_spring_channel && was_lost;
581 was_lost = lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700582
Austin Schuhe666dc62018-08-08 21:09:12 -0700583 spring->Iterate(unload, prime, fire, force_reset, force_move,
584 invalid_encoder_count <= 2, last_good_encoder);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700585
586 float spring_output = spring->output();
587
588 vesc_set_duty(4, -spring_output);
589 vesc_set_duty(5, spring_output);
590
Brian Silverman2de95d62018-03-31 12:32:24 -0700591 const float accelerometer = ReadAccelerometer();
592 (void)accelerometer;
593
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700594 /*
595 // Massive debug. Turn on for useful bits.
Brian Silverman2de95d62018-03-31 12:32:24 -0700596 printf("acc %d/1000\n", (int)(accelerometer / 1000));
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700597 if (!encoder.valid) {
598 printf("Stuck encoder: ADC %" PRIu16 " %" PRIu16
599 " enc %d/1000 %s mag %d\n",
600 adc_readings.sin, adc_readings.cos, (int)(encoder.angle * 1000),
601 encoder.valid ? "T" : "f",
602 (int)(hypot(ConvertEncoderChannel(adc_readings.sin),
603 ConvertEncoderChannel(adc_readings.cos)) *
604 1000));
605 }
Austin Schuhbcce26a2018-03-26 23:41:24 -0700606 static int i = 0;
607 ++i;
608 if (i > 20) {
609 i = 0;
Austin Schuhe666dc62018-08-08 21:09:12 -0700610 if (lost_spring_channel || lost_drive_channel) {
611 printf("200Hz loop, disabled %d %d %d %d %d %d\n",
Austin Schuhbcce26a2018-03-26 23:41:24 -0700612 (int)(convert_input_width(0) * 1000),
613 (int)(convert_input_width(1) * 1000),
614 (int)(convert_input_width(2) * 1000),
615 (int)(convert_input_width(3) * 1000),
Austin Schuhe666dc62018-08-08 21:09:12 -0700616 (int)(convert_input_width(4) * 1000),
617 (int)(convert_input_width(5) * 1000));
Austin Schuhbcce26a2018-03-26 23:41:24 -0700618 } else {
619 printf(
Austin Schuhe666dc62018-08-08 21:09:12 -0700620 "TODO(Austin): 200Hz loop %d %d %d %d %d %d, lr, %d, %d velocity %d
621 "
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700622 " state: %d, near %d angle %d goal %d to: %d ADC %" PRIu16
623 " %" PRIu16 " enc %d/1000 %s from %d\n",
Austin Schuhbcce26a2018-03-26 23:41:24 -0700624 (int)(convert_input_width(0) * 1000),
625 (int)(convert_input_width(1) * 1000),
626 (int)(convert_input_width(2) * 1000),
627 (int)(convert_input_width(3) * 1000),
628 (int)(convert_input_width(4) * 1000),
Austin Schuhe666dc62018-08-08 21:09:12 -0700629 (int)(convert_input_width(5) * 1000),
Austin Schuhbcce26a2018-03-26 23:41:24 -0700630 static_cast<int>(output.left_voltage * 100),
631 static_cast<int>(output.right_voltage * 100),
632 static_cast<int>(polydrivetrain->velocity() * 100),
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700633 static_cast<int>(spring->state()), static_cast<int>(spring->Near()),
634 static_cast<int>(spring->angle() * 1000),
635 static_cast<int>(spring->goal() * 1000),
636 static_cast<int>(spring->timeout()), adc_readings.sin,
637 adc_readings.cos, (int)(encoder.angle * 1000),
Austin Schuhbcce26a2018-03-26 23:41:24 -0700638 encoder.valid ? "T" : "f",
639 (int)(::std::sqrt(ConvertEncoderChannel(adc_readings.sin) *
640 ConvertEncoderChannel(adc_readings.sin) +
641 ConvertEncoderChannel(adc_readings.cos) *
642 ConvertEncoderChannel(adc_readings.cos)) *
643 1000));
644 }
645 }
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700646 */
Austin Schuhbcce26a2018-03-26 23:41:24 -0700647 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400648}
649
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700650} // namespace
651
652extern "C" {
653
654void *__stack_chk_guard = (void *)0x67111971;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700655void __stack_chk_fail(void);
656
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700657} // extern "C"
658
659extern "C" int main(void) {
660 // for background about this startup delay, please see these conversations
661 // https://forum.pjrc.com/threads/36606-startup-time-(400ms)?p=113980&viewfull=1#post113980
662 // https://forum.pjrc.com/threads/31290-Teensey-3-2-Teensey-Loader-1-24-Issues?p=87273&viewfull=1#post87273
663 delay(400);
664
665 // Set all interrupts to the second-lowest priority to start with.
666 for (int i = 0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_SANE_PRIORITY(i, 0xD);
667
668 // Now set priorities for all the ones we care about. They only have meaning
669 // relative to each other, which means centralizing them here makes it a lot
670 // more manageable.
671 NVIC_SET_SANE_PRIORITY(IRQ_USBOTG, 0x7);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400672 NVIC_SET_SANE_PRIORITY(IRQ_FTM0, 0xa);
673 NVIC_SET_SANE_PRIORITY(IRQ_FTM3, 0xa);
674 NVIC_SET_SANE_PRIORITY(IRQ_PIT_CH3, 0x5);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700675
676 // Builtin LED.
677 PERIPHERAL_BITBAND(GPIOC_PDOR, 5) = 1;
678 PORTC_PCR5 = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(1);
679 PERIPHERAL_BITBAND(GPIOC_PDDR, 5) = 1;
680
681 // Set up the CAN pins.
682 PORTA_PCR12 = PORT_PCR_DSE | PORT_PCR_MUX(2);
683 PORTA_PCR13 = PORT_PCR_DSE | PORT_PCR_MUX(2);
684
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700685 // PWM_IN0
686 // FTM0_CH0
687 PORTC_PCR1 = PORT_PCR_MUX(4);
688
689 // PWM_IN1
690 // FTM0_CH6
691 PORTD_PCR6 = PORT_PCR_MUX(4);
692
693 // PWM_IN2
694 // FTM0_CH4
695 PORTD_PCR4 = PORT_PCR_MUX(4);
696
697 // PWM_IN3
698 // FTM3_CH2
699 PORTD_PCR2 = PORT_PCR_MUX(4);
700
701 // PWM_IN4
702 // FTM0_CH2
703 PORTC_PCR3 = PORT_PCR_MUX(4);
704
Brian Silverman7f5f1442018-04-06 13:00:50 -0400705 // PWM_IN5
706 // FTM3_CH6
707 PORTC_PCR10 = PORT_PCR_MUX(3);
708
Brian Silverman2de95d62018-03-31 12:32:24 -0700709 // SPI0
710 // ACC_CS PCS0
711 PORTA_PCR14 = PORT_PCR_DSE | PORT_PCR_MUX(2);
712 // SCK
713 PORTA_PCR15 = PORT_PCR_DSE | PORT_PCR_MUX(2);
714 // MOSI
715 PORTA_PCR16 = PORT_PCR_DSE | PORT_PCR_MUX(2);
716 // MISO
717 PORTA_PCR17 = PORT_PCR_DSE | PORT_PCR_MUX(2);
718
719 SIM_SCGC6 |= SIM_SCGC6_SPI0;
720 SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_PCSIS(1) | SPI_MCR_CLR_TXF |
721 SPI_MCR_CLR_RXF | SPI_MCR_HALT;
722 // 60 MHz "protocol clock"
723 // 6ns CS setup
724 // 8ns CS hold
725 SPI0_CTAR0 = SPI_CTAR_FMSZ(15) | SPI_CTAR_CPOL /* Clock idles high */ |
726 SPI_CTAR_CPHA /* Data captured on trailing edge */ |
727 0 /* !LSBFE MSB first */ |
728 SPI_CTAR_PCSSCK(0) /* PCS->SCK prescaler = 1 */ |
729 SPI_CTAR_PASC(0) /* SCK->PCS prescaler = 1 */ |
730 SPI_CTAR_PDT(0) /* PCS->PCS prescaler = 1 */ |
731 SPI_CTAR_PBR(0) /* baud prescaler = 1 */ |
732 SPI_CTAR_CSSCK(0) /* PCS->SCK 2/60MHz = 33.33ns */ |
733 SPI_CTAR_ASC(0) /* SCK->PCS 2/60MHz = 33.33ns */ |
734 SPI_CTAR_DT(2) /* PCS->PSC 8/60MHz = 133.33ns */ |
735 SPI_CTAR_BR(2) /* BR 60MHz/6 = 10MHz */;
736
737 SPI0_MCR &= ~SPI_MCR_HALT;
738
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700739 delay(100);
740
Brian Silverman4787a6e2018-10-06 16:00:54 -0700741 PrintingParameters printing_parameters;
742 printing_parameters.dedicated_usb = true;
743 const ::std::unique_ptr<PrintingImplementation> printing =
744 CreatePrinting(printing_parameters);
745 printing->Initialize();
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700746
Brian Silvermana3a172b2018-03-24 03:53:32 -0400747 SIM_SCGC6 |= SIM_SCGC6_PIT;
748 // Workaround for errata e7914.
749 (void)PIT_MCR;
750 PIT_MCR = 0;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700751 PIT_LDVAL3 = (BUS_CLOCK_FREQUENCY / 200) - 1;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400752 PIT_TCTRL3 = PIT_TCTRL_TIE | PIT_TCTRL_TEN;
753
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700754 can_init(0, 1);
Brian Silvermana96c1a42018-05-12 12:11:31 -0700755 AdcInitSimple();
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700756 SetupPwmFtm(FTM0);
757 SetupPwmFtm(FTM3);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700758
Austin Schuhbcce26a2018-03-26 23:41:24 -0700759 PolyDrivetrain<float> polydrivetrain(GetDrivetrainConfig(), nullptr);
760 global_polydrivetrain.store(&polydrivetrain, ::std::memory_order_release);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700761 Spring spring;
762 global_spring.store(&spring, ::std::memory_order_release);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700763
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700764 // Leave the LEDs on for a bit longer.
765 delay(300);
766 printf("Done starting up\n");
767
Brian Silverman2de95d62018-03-31 12:32:24 -0700768 AccelerometerInit();
769 printf("Accelerometer init %s\n", accelerometer_inited ? "success" : "fail");
770
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700771 // Done starting up, now turn the LED off.
772 PERIPHERAL_BITBAND(GPIOC_PDOR, 5) = 0;
773
Brian Silvermana3a172b2018-03-24 03:53:32 -0400774 NVIC_ENABLE_IRQ(IRQ_FTM0);
775 NVIC_ENABLE_IRQ(IRQ_FTM3);
776 NVIC_ENABLE_IRQ(IRQ_PIT_CH3);
Austin Schuhe666dc62018-08-08 21:09:12 -0700777 printf("Done starting up2\n");
Brian Silvermana3a172b2018-03-24 03:53:32 -0400778
Austin Schuhe666dc62018-08-08 21:09:12 -0700779 //DoReceiverTest2();
Austin Schuhbcce26a2018-03-26 23:41:24 -0700780 while (true) {
781 }
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700782
783 return 0;
784}
785
786void __stack_chk_fail(void) {
787 while (true) {
788 GPIOC_PSOR = (1 << 5);
789 printf("Stack corruption detected\n");
790 delay(1000);
791 GPIOC_PCOR = (1 << 5);
792 delay(1000);
793 }
794}
795
796} // namespace motors
797} // namespace frc971