blob: 5f3af0a1f7207743a2aefafa6cbd8248d0f283ef [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::constants::ShifterHallEffect;
Alex Perrycb7da4b2019-08-28 19:35:56 -070026using ::frc971::control_loops::drivetrain::DrivetrainConfig;
27using ::frc971::control_loops::drivetrain::OutputT;
28using ::frc971::control_loops::drivetrain::PolyDrivetrain;
Austin Schuh4fae0fc2018-03-27 23:51:42 -070029using ::motors::seems_reasonable::Spring;
Austin Schuhbcce26a2018-03-26 23:41:24 -070030
Austin Schuhbb735b72019-01-03 12:58:41 -080031namespace chrono = ::std::chrono;
32
Brian Silverman9ed2cf12018-05-12 13:06:38 -070033struct SimpleAdcReadings {
34 uint16_t sin, cos;
35};
36
37void AdcInitSimple() {
38 AdcInitCommon();
39
40 // ENC_SIN ADC0_SE23
41 // ENC_COS ADC1_SE23
42}
43
44SimpleAdcReadings AdcReadSimple(const DisableInterrupts &) {
45 SimpleAdcReadings r;
46
47 ADC0_SC1A = 23;
48 ADC1_SC1A = 23;
49 while (!(ADC0_SC1A & ADC_SC1_COCO)) {
50 }
51 while (!(ADC1_SC1A & ADC_SC1_COCO)) {
52 }
53 r.sin = ADC0_RA;
54 r.cos = ADC1_RA;
55
56 return r;
57}
58
Austin Schuhbcce26a2018-03-26 23:41:24 -070059const ShifterHallEffect kThreeStateDriveShifter{0.0, 0.0, 0.25, 0.75};
60
61const DrivetrainConfig<float> &GetDrivetrainConfig() {
62 static DrivetrainConfig<float> kDrivetrainConfig{
63 ::frc971::control_loops::drivetrain::ShifterType::NO_SHIFTER,
64 ::frc971::control_loops::drivetrain::LoopType::OPEN_LOOP,
65 ::frc971::control_loops::drivetrain::GyroType::SPARTAN_GYRO,
66 ::frc971::control_loops::drivetrain::IMUType::IMU_X,
67
68 ::motors::seems_reasonable::MakeDrivetrainLoop,
69 ::motors::seems_reasonable::MakeVelocityDrivetrainLoop,
70 ::std::function<StateFeedbackLoop<7, 2, 4, float>()>(),
71
Austin Schuhbb735b72019-01-03 12:58:41 -080072 chrono::duration_cast<chrono::nanoseconds>(
73 chrono::duration<float>(::motors::seems_reasonable::kDt)),
74 ::motors::seems_reasonable::kRobotRadius,
Austin Schuhbcce26a2018-03-26 23:41:24 -070075 ::motors::seems_reasonable::kWheelRadius, ::motors::seems_reasonable::kV,
76
77 ::motors::seems_reasonable::kHighGearRatio,
Austin Schuhe6a9fdf2019-01-12 16:05:43 -080078 ::motors::seems_reasonable::kLowGearRatio,
79 ::motors::seems_reasonable::kJ,
80 ::motors::seems_reasonable::kMass,
81 kThreeStateDriveShifter,
Austin Schuhbcce26a2018-03-26 23:41:24 -070082 kThreeStateDriveShifter, true /* default_high_gear */,
83 0 /* down_offset if using constants use
84 constants::GetValues().down_error */, 0.8 /* wheel_non_linearity */,
85 1.2 /* quickturn_wheel_multiplier */, 1.5 /* wheel_multiplier */,
86 };
87
88 return kDrivetrainConfig;
89};
90
91
Austin Schuhbcce26a2018-03-26 23:41:24 -070092::std::atomic<PolyDrivetrain<float> *> global_polydrivetrain{nullptr};
Austin Schuh4fae0fc2018-03-27 23:51:42 -070093::std::atomic<Spring *> global_spring{nullptr};
Austin Schuhbcce26a2018-03-26 23:41:24 -070094
Brian Silvermana3a172b2018-03-24 03:53:32 -040095// Last width we received on each channel.
Brian Silverman7f5f1442018-04-06 13:00:50 -040096uint16_t pwm_input_widths[6];
Brian Silvermana3a172b2018-03-24 03:53:32 -040097// When we received a pulse on each channel in milliseconds.
Brian Silverman7f5f1442018-04-06 13:00:50 -040098uint32_t pwm_input_times[6];
Brian Silvermana3a172b2018-03-24 03:53:32 -040099
Austin Schuhbcce26a2018-03-26 23:41:24 -0700100constexpr int kChannelTimeout = 100;
101
102bool lost_channel(int channel) {
103 DisableInterrupts disable_interrupts;
104 if (time_after(millis(),
105 time_add(pwm_input_times[channel], kChannelTimeout))) {
106 return true;
107 }
108 return false;
109}
110
Brian Silvermana3a172b2018-03-24 03:53:32 -0400111// Returns the most recently captured value for the specified input channel
112// scaled from -1 to 1, or 0 if it was captured over 100ms ago.
113float convert_input_width(int channel) {
114 uint16_t width;
115 {
116 DisableInterrupts disable_interrupts;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700117 if (time_after(millis(),
118 time_add(pwm_input_times[channel], kChannelTimeout))) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400119 return 0;
120 }
121
122 width = pwm_input_widths[channel];
123 }
124
125 // Values measured with a channel mapped to a button.
126 static constexpr uint16_t kMinWidth = 4133;
127 static constexpr uint16_t kMaxWidth = 7177;
128 if (width < kMinWidth) {
129 width = kMinWidth;
130 } else if (width > kMaxWidth) {
131 width = kMaxWidth;
132 }
133 return (static_cast<float>(2 * (width - kMinWidth)) /
134 static_cast<float>(kMaxWidth - kMinWidth)) -
135 1.0f;
136}
137
138// Sends a SET_RPM command to the specified VESC.
139// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
140// bandwidth.
141void vesc_set_rpm(int vesc_id, float rpm) {
142 const int32_t rpm_int = rpm;
143 uint32_t id = CAN_EFF_FLAG;
144 id |= vesc_id;
145 id |= (0x03 /* SET_RPM */) << 8;
146 uint8_t data[4] = {
147 static_cast<uint8_t>((rpm_int >> 24) & 0xFF),
148 static_cast<uint8_t>((rpm_int >> 16) & 0xFF),
149 static_cast<uint8_t>((rpm_int >> 8) & 0xFF),
150 static_cast<uint8_t>((rpm_int >> 0) & 0xFF),
151 };
152 can_send(id, data, sizeof(data), 2 + vesc_id);
153}
154
155// Sends a SET_CURRENT command to the specified VESC.
156// current is in amps.
157// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
158// bandwidth.
159void vesc_set_current(int vesc_id, float current) {
Austin Schuhbcce26a2018-03-26 23:41:24 -0700160 constexpr float kMaxCurrent = 80.0f;
161 const int32_t current_int =
162 ::std::max(-kMaxCurrent, ::std::min(kMaxCurrent, current)) * 1000.0f;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400163 uint32_t id = CAN_EFF_FLAG;
164 id |= vesc_id;
165 id |= (0x01 /* SET_CURRENT */) << 8;
166 uint8_t data[4] = {
167 static_cast<uint8_t>((current_int >> 24) & 0xFF),
168 static_cast<uint8_t>((current_int >> 16) & 0xFF),
169 static_cast<uint8_t>((current_int >> 8) & 0xFF),
170 static_cast<uint8_t>((current_int >> 0) & 0xFF),
171 };
172 can_send(id, data, sizeof(data), 2 + vesc_id);
173}
174
Brian Silverman4d1e5272018-03-26 03:18:42 -0400175// Sends a SET_DUTY command to the specified VESC.
176// duty is from -1 to 1.
177// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
178// bandwidth.
179void vesc_set_duty(int vesc_id, float duty) {
Austin Schuhbcce26a2018-03-26 23:41:24 -0700180 constexpr int32_t kMaxDuty = 99999;
181 const int32_t duty_int = ::std::max(
182 -kMaxDuty, ::std::min(kMaxDuty, static_cast<int32_t>(duty * 100000.0f)));
Brian Silverman4d1e5272018-03-26 03:18:42 -0400183 uint32_t id = CAN_EFF_FLAG;
184 id |= vesc_id;
185 id |= (0x00 /* SET_DUTY */) << 8;
186 uint8_t data[4] = {
187 static_cast<uint8_t>((duty_int >> 24) & 0xFF),
188 static_cast<uint8_t>((duty_int >> 16) & 0xFF),
189 static_cast<uint8_t>((duty_int >> 8) & 0xFF),
190 static_cast<uint8_t>((duty_int >> 0) & 0xFF),
191 };
192 can_send(id, data, sizeof(data), 2 + vesc_id);
193}
194
Brian Silverman6c8b88b2018-09-03 18:17:02 -0700195// TODO(Brian): Move these two test functions somewhere else.
196__attribute__((unused)) void DoVescTest() {
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700197 uint32_t time = micros();
198 while (true) {
199 for (int i = 0; i < 6; ++i) {
200 const uint32_t end = time_add(time, 500000);
201 while (true) {
202 const bool done = time_after(micros(), end);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700203 float current;
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700204 if (done) {
205 current = -6;
206 } else {
207 current = 6;
208 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400209 vesc_set_current(i, current);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700210 if (done) {
211 break;
212 }
213 delay(5);
214 }
215 time = end;
216 }
217 }
218}
219
Brian Silverman6c8b88b2018-09-03 18:17:02 -0700220__attribute__((unused)) void DoReceiverTest2() {
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700221 static constexpr float kMaxRpm = 10000.0f;
222 while (true) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400223 const bool flip = convert_input_width(2) > 0;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700224
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700225 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400226 const float value = convert_input_width(0);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700227
228 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400229 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700230 if (flip) {
231 rpm *= -1.0f;
232 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400233 vesc_set_rpm(0, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700234 }
235
236 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400237 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700238 if (flip) {
239 rpm *= -1.0f;
240 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400241 vesc_set_rpm(1, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700242 }
243 }
244
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700245 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400246 const float value = convert_input_width(1);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700247
248 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400249 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700250 if (flip) {
251 rpm *= -1.0f;
252 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400253 vesc_set_rpm(2, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700254 }
255
256 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400257 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700258 if (flip) {
259 rpm *= -1.0f;
260 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400261 vesc_set_rpm(3, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700262 }
263 }
264
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700265 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400266 const float value = convert_input_width(4);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700267
268 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400269 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700270 if (flip) {
271 rpm *= -1.0f;
272 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400273 vesc_set_rpm(4, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700274 }
275
276 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400277 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700278 if (flip) {
279 rpm *= -1.0f;
280 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400281 vesc_set_rpm(5, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700282 }
283 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400284 // Give the CAN frames a chance to go out.
285 delay(5);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700286 }
287}
288
289void SetupPwmFtm(BigFTM *ftm) {
290 ftm->MODE = FTM_MODE_WPDIS;
291 ftm->MODE = FTM_MODE_WPDIS | FTM_MODE_FTMEN;
292 ftm->SC = FTM_SC_CLKS(0) /* Disable counting for now */;
293
294 // Can't change MOD according to the reference manual ("The Dual Edge Capture
295 // mode must be used with ... the FTM counter in Free running counter.").
296 ftm->MOD = 0xFFFF;
297
298 // Capturing rising edge.
299 ftm->C0SC = FTM_CSC_MSA | FTM_CSC_ELSA;
300 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400301 ftm->C1SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700302
303 // Capturing rising edge.
304 ftm->C2SC = FTM_CSC_MSA | FTM_CSC_ELSA;
305 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400306 ftm->C3SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700307
308 // Capturing rising edge.
309 ftm->C4SC = FTM_CSC_MSA | FTM_CSC_ELSA;
310 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400311 ftm->C5SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700312
313 // Capturing rising edge.
314 ftm->C6SC = FTM_CSC_MSA | FTM_CSC_ELSA;
315 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400316 ftm->C7SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700317
Brian Silvermana3a172b2018-03-24 03:53:32 -0400318 (void)ftm->STATUS;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700319 ftm->STATUS = 0x00;
320
321 ftm->COMBINE = FTM_COMBINE_DECAP3 | FTM_COMBINE_DECAPEN3 |
322 FTM_COMBINE_DECAP2 | FTM_COMBINE_DECAPEN2 |
323 FTM_COMBINE_DECAP1 | FTM_COMBINE_DECAPEN1 |
324 FTM_COMBINE_DECAP0 | FTM_COMBINE_DECAPEN0;
325
326 // 34.95ms max period before it starts wrapping and being weird.
327 ftm->SC = FTM_SC_CLKS(1) /* Use the system clock */ |
328 FTM_SC_PS(4) /* Prescaler=32 */;
329
330 ftm->MODE &= ~FTM_MODE_WPDIS;
331}
332
Brian Silverman2de95d62018-03-31 12:32:24 -0700333struct AccelerometerResult {
334 uint16_t result;
335 bool success;
336};
337
338// Does a transfer on the accelerometer. Returns the resulting frame, or a
339// failure if it takes until after end_micros.
340AccelerometerResult AccelerometerTransfer(uint16_t data, uint32_t end_micros) {
341 SPI0_SR = SPI_SR_RFDF;
342 SPI0_PUSHR = SPI_PUSHR_PCS(1) | data;
343
344 while (!(SPI0_SR & SPI_SR_RFDF)) {
345 if (time_after(micros(), end_micros)) {
346 return {0, false};
347 }
348 }
349 const uint32_t popr = SPI0_POPR;
350 SPI0_SR = SPI_SR_RFDF;
351 return {static_cast<uint16_t>(popr & 0xFFFF), true};
352}
353
354constexpr uint32_t kAccelerometerTimeout = 500;
355
356bool AccelerometerWrite(uint8_t address, uint8_t data, uint32_t end_micros) {
357 const AccelerometerResult r = AccelerometerTransfer(
358 (static_cast<uint16_t>(address) << 8) | static_cast<uint16_t>(data),
359 end_micros);
360 return r.success;
361}
362
363AccelerometerResult AccelerometerRead(uint8_t address, uint32_t end_micros) {
364 AccelerometerResult r = AccelerometerTransfer(
365 (static_cast<uint16_t>(address) << 8) | UINT16_C(0x8000), end_micros);
366 r.result = r.result & UINT16_C(0xFF);
367 return r;
368}
369
370bool accelerometer_inited = false;
371
372void AccelerometerInit() {
373 accelerometer_inited = false;
374 const uint32_t end_micros = time_add(micros(), kAccelerometerTimeout);
375 {
376 const auto who_am_i = AccelerometerRead(0xF, end_micros);
377 if (!who_am_i.success) {
378 return;
379 }
380 if (who_am_i.result != 0x32) {
381 return;
382 }
383 }
384 if (!AccelerometerWrite(
385 0x20, (1 << 5) /* Normal mode */ | (1 << 3) /* 100 Hz */ |
386 (1 << 2) /* Z enabled */ | (1 << 1) /* Y enabled */ |
387 (1 << 0) /* X enabled */,
388 end_micros)) {
389 }
390 // If want to read LSB, need to enable BDU to avoid splitting reads.
391 if (!AccelerometerWrite(0x23, (0 << 6) /* Data LSB at lower address */ |
392 (3 << 4) /* 400g full scale */ |
393 (0 << 0) /* 4-wire interface */,
394 end_micros)) {
395 }
396 accelerometer_inited = true;
397}
398
399float AccelerometerConvert(uint16_t value) {
400 return static_cast<float>(400.0 / 65536.0) * static_cast<float>(value);
401}
402
403// Returns the total acceleration (in any direction) or 0 if there's an error.
404float ReadAccelerometer() {
405 if (!accelerometer_inited) {
406 AccelerometerInit();
407 return 0;
408 }
409
410 const uint32_t end_micros = time_add(micros(), kAccelerometerTimeout);
411 const auto x = AccelerometerRead(0x29, end_micros);
412 const auto y = AccelerometerRead(0x2B, end_micros);
413 const auto z = AccelerometerRead(0x2D, end_micros);
414 if (!x.success || !y.success || !z.success) {
415 accelerometer_inited = false;
416 return 0;
417 }
418
419 const float x_g = AccelerometerConvert(x.result);
420 const float y_g = AccelerometerConvert(y.result);
421 const float z_g = AccelerometerConvert(z.result);
422 return ::std::sqrt(x_g * x_g + y_g * y_g + z_g * z_g);
423}
424
Brian Silvermana3a172b2018-03-24 03:53:32 -0400425extern "C" void ftm0_isr() {
426 while (true) {
427 const uint32_t status = FTM0->STATUS;
428 if (status == 0) {
429 return;
430 }
431
432 if (status & (1 << 1)) {
433 const uint32_t start = FTM0->C0V;
434 const uint32_t end = FTM0->C1V;
435 pwm_input_widths[0] = (end - start) & 0xFFFF;
436 pwm_input_times[0] = millis();
437 }
438 if (status & (1 << 7)) {
439 const uint32_t start = FTM0->C6V;
440 const uint32_t end = FTM0->C7V;
441 pwm_input_widths[1] = (end - start) & 0xFFFF;
442 pwm_input_times[1] = millis();
443 }
444 if (status & (1 << 5)) {
445 const uint32_t start = FTM0->C4V;
446 const uint32_t end = FTM0->C5V;
447 pwm_input_widths[2] = (end - start) & 0xFFFF;
448 pwm_input_times[2] = millis();
449 }
450 if (status & (1 << 3)) {
451 const uint32_t start = FTM0->C2V;
452 const uint32_t end = FTM0->C3V;
453 pwm_input_widths[4] = (end - start) & 0xFFFF;
454 pwm_input_times[4] = millis();
455 }
456
457 FTM0->STATUS = 0;
458 }
459}
460
461extern "C" void ftm3_isr() {
462 while (true) {
463 const uint32_t status = FTM3->STATUS;
464 if (status == 0) {
465 return;
466 }
467
468 if (status & (1 << 3)) {
469 const uint32_t start = FTM3->C2V;
470 const uint32_t end = FTM3->C3V;
471 pwm_input_widths[3] = (end - start) & 0xFFFF;
472 pwm_input_times[3] = millis();
473 }
Brian Silverman7f5f1442018-04-06 13:00:50 -0400474 if (status & (1 << 7)) {
475 const uint32_t start = FTM3->C6V;
476 const uint32_t end = FTM3->C7V;
477 pwm_input_widths[5] = (end - start) & 0xFFFF;
478 pwm_input_times[5] = millis();
479 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400480
481 FTM3->STATUS = 0;
482 }
483}
484
485float ConvertEncoderChannel(uint16_t reading) {
486 // Theoretical values based on the datasheet are 931 and 2917.
487 // With these values, the magnitude ranges from 0.99-1.03, which works fine
488 // (the encoder's output appears to get less accurate in one quadrant for some
489 // reason, hence the variation).
490 static constexpr uint16_t kMin = 802, kMax = 3088;
491 if (reading < kMin) {
492 reading = kMin;
493 } else if (reading > kMax) {
494 reading = kMax;
495 }
496 return (static_cast<float>(2 * (reading - kMin)) /
497 static_cast<float>(kMax - kMin)) -
498 1.0f;
499}
500
501struct EncoderReading {
Brian Silvermana96c1a42018-05-12 12:11:31 -0700502 EncoderReading(const SimpleAdcReadings &adc_readings) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400503 const float sin = ConvertEncoderChannel(adc_readings.sin);
504 const float cos = ConvertEncoderChannel(adc_readings.cos);
505
Austin Schuhbcce26a2018-03-26 23:41:24 -0700506 const float magnitude = hypot(sin, cos);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400507 const float magnitude_error = ::std::abs(magnitude - 1.0f);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700508 valid = magnitude_error < 0.30f;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400509
510 angle = ::std::atan2(sin, cos);
511 }
512
513 // Angle in radians, in [-pi, pi].
514 float angle;
515
516 bool valid;
517};
518
519extern "C" void pit3_isr() {
520 PIT_TFLG3 = 1;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700521 PolyDrivetrain<float> *polydrivetrain =
522 global_polydrivetrain.load(::std::memory_order_acquire);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700523 Spring *spring = global_spring.load(::std::memory_order_acquire);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400524
Brian Silvermana96c1a42018-05-12 12:11:31 -0700525 SimpleAdcReadings adc_readings;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400526 {
527 DisableInterrupts disable_interrupts;
Brian Silvermana96c1a42018-05-12 12:11:31 -0700528 adc_readings = AdcReadSimple(disable_interrupts);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400529 }
530
531 EncoderReading encoder(adc_readings);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700532 static float last_good_encoder = 0.0f;
533 static int invalid_encoder_count = 0;
534 if (encoder.valid) {
535 last_good_encoder = encoder.angle;
536 invalid_encoder_count = 0;
537 } else {
538 ++invalid_encoder_count;
539 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400540
Austin Schuhe666dc62018-08-08 21:09:12 -0700541 const bool lost_spring_channel = lost_channel(2) || lost_channel(3) ||
542 lost_channel(4) || lost_channel(5) ||
543 (convert_input_width(4) < 0.5f);
544
545 const bool lost_drive_channel = lost_channel(0) || lost_channel(1) ||
546 (::std::abs(convert_input_width(4)) < 0.5f);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700547
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700548 if (polydrivetrain != nullptr && spring != nullptr) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700549 float throttle;
550 float wheel;
Austin Schuhe666dc62018-08-08 21:09:12 -0700551 if (lost_drive_channel) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 throttle = 0.0f;
553 wheel = 0.0f;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700554 } else {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555 throttle = convert_input_width(1);
556 wheel = -convert_input_width(0);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700557 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558 const bool quickturn = ::std::abs(polydrivetrain->velocity()) < 0.25f;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700559
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560 OutputT output;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700561
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562 polydrivetrain->SetGoal(wheel, throttle, quickturn, false);
Austin Schuheeec74a2019-01-27 20:58:59 -0800563 polydrivetrain->Update(12.0f);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700564 polydrivetrain->SetOutput(&output);
565
566 vesc_set_duty(0, -output.left_voltage / 12.0f);
567 vesc_set_duty(1, -output.left_voltage / 12.0f);
568
569 vesc_set_duty(2, output.right_voltage / 12.0f);
570 vesc_set_duty(3, output.right_voltage / 12.0f);
571
Austin Schuhe666dc62018-08-08 21:09:12 -0700572 const bool prime = convert_input_width(2) > 0.1f;
573 const bool fire = convert_input_width(3) > 0.1f;
574 const bool force_move =
575 (convert_input_width(5) > 0.1f) && !lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700576
Austin Schuhe666dc62018-08-08 21:09:12 -0700577 bool unload = lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700578 static bool was_lost = true;
Austin Schuhe666dc62018-08-08 21:09:12 -0700579 bool force_reset = !lost_spring_channel && was_lost;
580 was_lost = lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700581
Austin Schuhe666dc62018-08-08 21:09:12 -0700582 spring->Iterate(unload, prime, fire, force_reset, force_move,
583 invalid_encoder_count <= 2, last_good_encoder);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700584
585 float spring_output = spring->output();
586
587 vesc_set_duty(4, -spring_output);
588 vesc_set_duty(5, spring_output);
589
Brian Silverman2de95d62018-03-31 12:32:24 -0700590 const float accelerometer = ReadAccelerometer();
591 (void)accelerometer;
592
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700593 /*
594 // Massive debug. Turn on for useful bits.
Brian Silverman2de95d62018-03-31 12:32:24 -0700595 printf("acc %d/1000\n", (int)(accelerometer / 1000));
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700596 if (!encoder.valid) {
597 printf("Stuck encoder: ADC %" PRIu16 " %" PRIu16
598 " enc %d/1000 %s mag %d\n",
599 adc_readings.sin, adc_readings.cos, (int)(encoder.angle * 1000),
600 encoder.valid ? "T" : "f",
601 (int)(hypot(ConvertEncoderChannel(adc_readings.sin),
602 ConvertEncoderChannel(adc_readings.cos)) *
603 1000));
604 }
Austin Schuhbcce26a2018-03-26 23:41:24 -0700605 static int i = 0;
606 ++i;
607 if (i > 20) {
608 i = 0;
Austin Schuhe666dc62018-08-08 21:09:12 -0700609 if (lost_spring_channel || lost_drive_channel) {
610 printf("200Hz loop, disabled %d %d %d %d %d %d\n",
Austin Schuhbcce26a2018-03-26 23:41:24 -0700611 (int)(convert_input_width(0) * 1000),
612 (int)(convert_input_width(1) * 1000),
613 (int)(convert_input_width(2) * 1000),
614 (int)(convert_input_width(3) * 1000),
Austin Schuhe666dc62018-08-08 21:09:12 -0700615 (int)(convert_input_width(4) * 1000),
616 (int)(convert_input_width(5) * 1000));
Austin Schuhbcce26a2018-03-26 23:41:24 -0700617 } else {
618 printf(
Austin Schuhe666dc62018-08-08 21:09:12 -0700619 "TODO(Austin): 200Hz loop %d %d %d %d %d %d, lr, %d, %d velocity %d
620 "
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700621 " state: %d, near %d angle %d goal %d to: %d ADC %" PRIu16
622 " %" PRIu16 " enc %d/1000 %s from %d\n",
Austin Schuhbcce26a2018-03-26 23:41:24 -0700623 (int)(convert_input_width(0) * 1000),
624 (int)(convert_input_width(1) * 1000),
625 (int)(convert_input_width(2) * 1000),
626 (int)(convert_input_width(3) * 1000),
627 (int)(convert_input_width(4) * 1000),
Austin Schuhe666dc62018-08-08 21:09:12 -0700628 (int)(convert_input_width(5) * 1000),
Austin Schuhbcce26a2018-03-26 23:41:24 -0700629 static_cast<int>(output.left_voltage * 100),
630 static_cast<int>(output.right_voltage * 100),
631 static_cast<int>(polydrivetrain->velocity() * 100),
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700632 static_cast<int>(spring->state()), static_cast<int>(spring->Near()),
633 static_cast<int>(spring->angle() * 1000),
634 static_cast<int>(spring->goal() * 1000),
635 static_cast<int>(spring->timeout()), adc_readings.sin,
636 adc_readings.cos, (int)(encoder.angle * 1000),
Austin Schuhbcce26a2018-03-26 23:41:24 -0700637 encoder.valid ? "T" : "f",
638 (int)(::std::sqrt(ConvertEncoderChannel(adc_readings.sin) *
639 ConvertEncoderChannel(adc_readings.sin) +
640 ConvertEncoderChannel(adc_readings.cos) *
641 ConvertEncoderChannel(adc_readings.cos)) *
642 1000));
643 }
644 }
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700645 */
Austin Schuhbcce26a2018-03-26 23:41:24 -0700646 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400647}
648
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700649} // namespace
650
651extern "C" {
652
653void *__stack_chk_guard = (void *)0x67111971;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700654void __stack_chk_fail(void);
655
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700656} // extern "C"
657
658extern "C" int main(void) {
659 // for background about this startup delay, please see these conversations
660 // https://forum.pjrc.com/threads/36606-startup-time-(400ms)?p=113980&viewfull=1#post113980
661 // https://forum.pjrc.com/threads/31290-Teensey-3-2-Teensey-Loader-1-24-Issues?p=87273&viewfull=1#post87273
662 delay(400);
663
664 // Set all interrupts to the second-lowest priority to start with.
665 for (int i = 0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_SANE_PRIORITY(i, 0xD);
666
667 // Now set priorities for all the ones we care about. They only have meaning
668 // relative to each other, which means centralizing them here makes it a lot
669 // more manageable.
670 NVIC_SET_SANE_PRIORITY(IRQ_USBOTG, 0x7);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400671 NVIC_SET_SANE_PRIORITY(IRQ_FTM0, 0xa);
672 NVIC_SET_SANE_PRIORITY(IRQ_FTM3, 0xa);
673 NVIC_SET_SANE_PRIORITY(IRQ_PIT_CH3, 0x5);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700674
675 // Builtin LED.
676 PERIPHERAL_BITBAND(GPIOC_PDOR, 5) = 1;
677 PORTC_PCR5 = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(1);
678 PERIPHERAL_BITBAND(GPIOC_PDDR, 5) = 1;
679
680 // Set up the CAN pins.
681 PORTA_PCR12 = PORT_PCR_DSE | PORT_PCR_MUX(2);
682 PORTA_PCR13 = PORT_PCR_DSE | PORT_PCR_MUX(2);
683
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700684 // PWM_IN0
685 // FTM0_CH0
686 PORTC_PCR1 = PORT_PCR_MUX(4);
687
688 // PWM_IN1
689 // FTM0_CH6
690 PORTD_PCR6 = PORT_PCR_MUX(4);
691
692 // PWM_IN2
693 // FTM0_CH4
694 PORTD_PCR4 = PORT_PCR_MUX(4);
695
696 // PWM_IN3
697 // FTM3_CH2
698 PORTD_PCR2 = PORT_PCR_MUX(4);
699
700 // PWM_IN4
701 // FTM0_CH2
702 PORTC_PCR3 = PORT_PCR_MUX(4);
703
Brian Silverman7f5f1442018-04-06 13:00:50 -0400704 // PWM_IN5
705 // FTM3_CH6
706 PORTC_PCR10 = PORT_PCR_MUX(3);
707
Brian Silverman2de95d62018-03-31 12:32:24 -0700708 // SPI0
709 // ACC_CS PCS0
710 PORTA_PCR14 = PORT_PCR_DSE | PORT_PCR_MUX(2);
711 // SCK
712 PORTA_PCR15 = PORT_PCR_DSE | PORT_PCR_MUX(2);
713 // MOSI
714 PORTA_PCR16 = PORT_PCR_DSE | PORT_PCR_MUX(2);
715 // MISO
716 PORTA_PCR17 = PORT_PCR_DSE | PORT_PCR_MUX(2);
717
718 SIM_SCGC6 |= SIM_SCGC6_SPI0;
719 SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_PCSIS(1) | SPI_MCR_CLR_TXF |
720 SPI_MCR_CLR_RXF | SPI_MCR_HALT;
721 // 60 MHz "protocol clock"
722 // 6ns CS setup
723 // 8ns CS hold
724 SPI0_CTAR0 = SPI_CTAR_FMSZ(15) | SPI_CTAR_CPOL /* Clock idles high */ |
725 SPI_CTAR_CPHA /* Data captured on trailing edge */ |
726 0 /* !LSBFE MSB first */ |
727 SPI_CTAR_PCSSCK(0) /* PCS->SCK prescaler = 1 */ |
728 SPI_CTAR_PASC(0) /* SCK->PCS prescaler = 1 */ |
729 SPI_CTAR_PDT(0) /* PCS->PCS prescaler = 1 */ |
730 SPI_CTAR_PBR(0) /* baud prescaler = 1 */ |
731 SPI_CTAR_CSSCK(0) /* PCS->SCK 2/60MHz = 33.33ns */ |
732 SPI_CTAR_ASC(0) /* SCK->PCS 2/60MHz = 33.33ns */ |
733 SPI_CTAR_DT(2) /* PCS->PSC 8/60MHz = 133.33ns */ |
734 SPI_CTAR_BR(2) /* BR 60MHz/6 = 10MHz */;
735
736 SPI0_MCR &= ~SPI_MCR_HALT;
737
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700738 delay(100);
739
Brian Silverman4787a6e2018-10-06 16:00:54 -0700740 PrintingParameters printing_parameters;
741 printing_parameters.dedicated_usb = true;
742 const ::std::unique_ptr<PrintingImplementation> printing =
743 CreatePrinting(printing_parameters);
744 printing->Initialize();
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700745
Brian Silvermana3a172b2018-03-24 03:53:32 -0400746 SIM_SCGC6 |= SIM_SCGC6_PIT;
747 // Workaround for errata e7914.
748 (void)PIT_MCR;
749 PIT_MCR = 0;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700750 PIT_LDVAL3 = (BUS_CLOCK_FREQUENCY / 200) - 1;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400751 PIT_TCTRL3 = PIT_TCTRL_TIE | PIT_TCTRL_TEN;
752
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700753 can_init(0, 1);
Brian Silvermana96c1a42018-05-12 12:11:31 -0700754 AdcInitSimple();
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700755 SetupPwmFtm(FTM0);
756 SetupPwmFtm(FTM3);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700757
Austin Schuhbcce26a2018-03-26 23:41:24 -0700758 PolyDrivetrain<float> polydrivetrain(GetDrivetrainConfig(), nullptr);
759 global_polydrivetrain.store(&polydrivetrain, ::std::memory_order_release);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700760 Spring spring;
761 global_spring.store(&spring, ::std::memory_order_release);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700762
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700763 // Leave the LEDs on for a bit longer.
764 delay(300);
765 printf("Done starting up\n");
766
Brian Silverman2de95d62018-03-31 12:32:24 -0700767 AccelerometerInit();
768 printf("Accelerometer init %s\n", accelerometer_inited ? "success" : "fail");
769
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700770 // Done starting up, now turn the LED off.
771 PERIPHERAL_BITBAND(GPIOC_PDOR, 5) = 0;
772
Brian Silvermana3a172b2018-03-24 03:53:32 -0400773 NVIC_ENABLE_IRQ(IRQ_FTM0);
774 NVIC_ENABLE_IRQ(IRQ_FTM3);
775 NVIC_ENABLE_IRQ(IRQ_PIT_CH3);
Austin Schuhe666dc62018-08-08 21:09:12 -0700776 printf("Done starting up2\n");
Brian Silvermana3a172b2018-03-24 03:53:32 -0400777
Austin Schuhe666dc62018-08-08 21:09:12 -0700778 //DoReceiverTest2();
Austin Schuhbcce26a2018-03-26 23:41:24 -0700779 while (true) {
780 }
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700781
782 return 0;
783}
784
785void __stack_chk_fail(void) {
786 while (true) {
787 GPIOC_PSOR = (1 << 5);
788 printf("Stack corruption detected\n");
789 delay(1000);
790 GPIOC_PCOR = (1 << 5);
791 delay(1000);
792 }
793}
794
795} // namespace motors
796} // namespace frc971