blob: bb10353e1a933033f147ae37013e2f768a9a27b3 [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>
Philipp Schrader790cb542023-07-05 21:06:52 -07005
Brian Silverman54dd2fe2018-03-16 23:44:31 -07006#include <atomic>
Austin Schuhbb735b72019-01-03 12:58:41 -08007#include <chrono>
Brian Silverman54dd2fe2018-03-16 23:44:31 -07008#include <cmath>
9
Austin Schuh4fae0fc2018-03-27 23:51:42 -070010#include "frc971/control_loops/drivetrain/polydrivetrain.h"
Brian Silverman54dd2fe2018-03-16 23:44:31 -070011#include "motors/core/kinetis.h"
Brian Silvermana3a172b2018-03-24 03:53:32 -040012#include "motors/core/time.h"
Brian Silverman54dd2fe2018-03-16 23:44:31 -070013#include "motors/peripheral/adc.h"
14#include "motors/peripheral/can.h"
Brian Silvermana3a172b2018-03-24 03:53:32 -040015#include "motors/peripheral/configuration.h"
Brian Silverman4787a6e2018-10-06 16:00:54 -070016#include "motors/print/print.h"
Austin Schuh4fae0fc2018-03-27 23:51:42 -070017#include "motors/seems_reasonable/drivetrain_dog_motor_plant.h"
18#include "motors/seems_reasonable/polydrivetrain_dog_motor_plant.h"
19#include "motors/seems_reasonable/spring.h"
Brian Silverman54dd2fe2018-03-16 23:44:31 -070020#include "motors/util.h"
21
22namespace frc971 {
23namespace motors {
24namespace {
25
Austin Schuhbcce26a2018-03-26 23:41:24 -070026using ::frc971::constants::ShifterHallEffect;
Alex Perrycb7da4b2019-08-28 19:35:56 -070027using ::frc971::control_loops::drivetrain::DrivetrainConfig;
28using ::frc971::control_loops::drivetrain::OutputT;
29using ::frc971::control_loops::drivetrain::PolyDrivetrain;
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,
Philipp Schrader790cb542023-07-05 21:06:52 -070076 ::motors::seems_reasonable::kWheelRadius,
77 ::motors::seems_reasonable::kV,
Austin Schuhbcce26a2018-03-26 23:41:24 -070078
79 ::motors::seems_reasonable::kHighGearRatio,
Austin Schuhe6a9fdf2019-01-12 16:05:43 -080080 ::motors::seems_reasonable::kLowGearRatio,
81 ::motors::seems_reasonable::kJ,
82 ::motors::seems_reasonable::kMass,
83 kThreeStateDriveShifter,
Philipp Schrader790cb542023-07-05 21:06:52 -070084 kThreeStateDriveShifter,
85 true /* default_high_gear */,
Austin Schuhbcce26a2018-03-26 23:41:24 -070086 0 /* down_offset if using constants use
Philipp Schrader790cb542023-07-05 21:06:52 -070087 constants::GetValues().down_error */
88 ,
89 0.8 /* wheel_non_linearity */,
90 1.2 /* quickturn_wheel_multiplier */,
91 1.5 /* wheel_multiplier */,
Austin Schuhbcce26a2018-03-26 23:41:24 -070092 };
93
94 return kDrivetrainConfig;
95};
96
Austin Schuhbcce26a2018-03-26 23:41:24 -070097::std::atomic<PolyDrivetrain<float> *> global_polydrivetrain{nullptr};
Austin Schuh4fae0fc2018-03-27 23:51:42 -070098::std::atomic<Spring *> global_spring{nullptr};
Austin Schuhbcce26a2018-03-26 23:41:24 -070099
Brian Silvermana3a172b2018-03-24 03:53:32 -0400100// Last width we received on each channel.
Brian Silverman7f5f1442018-04-06 13:00:50 -0400101uint16_t pwm_input_widths[6];
Brian Silvermana3a172b2018-03-24 03:53:32 -0400102// When we received a pulse on each channel in milliseconds.
Brian Silverman7f5f1442018-04-06 13:00:50 -0400103uint32_t pwm_input_times[6];
Brian Silvermana3a172b2018-03-24 03:53:32 -0400104
Austin Schuhbcce26a2018-03-26 23:41:24 -0700105constexpr int kChannelTimeout = 100;
106
107bool lost_channel(int channel) {
108 DisableInterrupts disable_interrupts;
109 if (time_after(millis(),
110 time_add(pwm_input_times[channel], kChannelTimeout))) {
111 return true;
112 }
113 return false;
114}
115
Brian Silvermana3a172b2018-03-24 03:53:32 -0400116// Returns the most recently captured value for the specified input channel
117// scaled from -1 to 1, or 0 if it was captured over 100ms ago.
118float convert_input_width(int channel) {
119 uint16_t width;
120 {
121 DisableInterrupts disable_interrupts;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700122 if (time_after(millis(),
123 time_add(pwm_input_times[channel], kChannelTimeout))) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400124 return 0;
125 }
126
127 width = pwm_input_widths[channel];
128 }
129
130 // Values measured with a channel mapped to a button.
131 static constexpr uint16_t kMinWidth = 4133;
132 static constexpr uint16_t kMaxWidth = 7177;
133 if (width < kMinWidth) {
134 width = kMinWidth;
135 } else if (width > kMaxWidth) {
136 width = kMaxWidth;
137 }
138 return (static_cast<float>(2 * (width - kMinWidth)) /
139 static_cast<float>(kMaxWidth - kMinWidth)) -
140 1.0f;
141}
142
143// Sends a SET_RPM command to the specified VESC.
144// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
145// bandwidth.
146void vesc_set_rpm(int vesc_id, float rpm) {
147 const int32_t rpm_int = rpm;
148 uint32_t id = CAN_EFF_FLAG;
149 id |= vesc_id;
150 id |= (0x03 /* SET_RPM */) << 8;
151 uint8_t data[4] = {
152 static_cast<uint8_t>((rpm_int >> 24) & 0xFF),
153 static_cast<uint8_t>((rpm_int >> 16) & 0xFF),
154 static_cast<uint8_t>((rpm_int >> 8) & 0xFF),
155 static_cast<uint8_t>((rpm_int >> 0) & 0xFF),
156 };
157 can_send(id, data, sizeof(data), 2 + vesc_id);
158}
159
160// Sends a SET_CURRENT command to the specified VESC.
161// current is in amps.
162// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
163// bandwidth.
164void vesc_set_current(int vesc_id, float current) {
Austin Schuhbcce26a2018-03-26 23:41:24 -0700165 constexpr float kMaxCurrent = 80.0f;
166 const int32_t current_int =
167 ::std::max(-kMaxCurrent, ::std::min(kMaxCurrent, current)) * 1000.0f;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400168 uint32_t id = CAN_EFF_FLAG;
169 id |= vesc_id;
170 id |= (0x01 /* SET_CURRENT */) << 8;
171 uint8_t data[4] = {
172 static_cast<uint8_t>((current_int >> 24) & 0xFF),
173 static_cast<uint8_t>((current_int >> 16) & 0xFF),
174 static_cast<uint8_t>((current_int >> 8) & 0xFF),
175 static_cast<uint8_t>((current_int >> 0) & 0xFF),
176 };
177 can_send(id, data, sizeof(data), 2 + vesc_id);
178}
179
Brian Silverman4d1e5272018-03-26 03:18:42 -0400180// Sends a SET_DUTY command to the specified VESC.
181// duty is from -1 to 1.
182// Note that sending 6 VESC commands every 1ms doesn't quite fit in the CAN
183// bandwidth.
184void vesc_set_duty(int vesc_id, float duty) {
Austin Schuhbcce26a2018-03-26 23:41:24 -0700185 constexpr int32_t kMaxDuty = 99999;
186 const int32_t duty_int = ::std::max(
187 -kMaxDuty, ::std::min(kMaxDuty, static_cast<int32_t>(duty * 100000.0f)));
Brian Silverman4d1e5272018-03-26 03:18:42 -0400188 uint32_t id = CAN_EFF_FLAG;
189 id |= vesc_id;
190 id |= (0x00 /* SET_DUTY */) << 8;
191 uint8_t data[4] = {
192 static_cast<uint8_t>((duty_int >> 24) & 0xFF),
193 static_cast<uint8_t>((duty_int >> 16) & 0xFF),
194 static_cast<uint8_t>((duty_int >> 8) & 0xFF),
195 static_cast<uint8_t>((duty_int >> 0) & 0xFF),
196 };
197 can_send(id, data, sizeof(data), 2 + vesc_id);
198}
199
Brian Silverman6c8b88b2018-09-03 18:17:02 -0700200// TODO(Brian): Move these two test functions somewhere else.
201__attribute__((unused)) void DoVescTest() {
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700202 uint32_t time = micros();
203 while (true) {
204 for (int i = 0; i < 6; ++i) {
205 const uint32_t end = time_add(time, 500000);
206 while (true) {
207 const bool done = time_after(micros(), end);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700208 float current;
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700209 if (done) {
210 current = -6;
211 } else {
212 current = 6;
213 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400214 vesc_set_current(i, current);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700215 if (done) {
216 break;
217 }
218 delay(5);
219 }
220 time = end;
221 }
222 }
223}
224
Brian Silverman6c8b88b2018-09-03 18:17:02 -0700225__attribute__((unused)) void DoReceiverTest2() {
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700226 static constexpr float kMaxRpm = 10000.0f;
227 while (true) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400228 const bool flip = convert_input_width(2) > 0;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700229
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700230 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400231 const float value = convert_input_width(0);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700232
233 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400234 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700235 if (flip) {
236 rpm *= -1.0f;
237 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400238 vesc_set_rpm(0, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700239 }
240
241 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400242 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700243 if (flip) {
244 rpm *= -1.0f;
245 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400246 vesc_set_rpm(1, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700247 }
248 }
249
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700250 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400251 const float value = convert_input_width(1);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700252
253 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400254 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700255 if (flip) {
256 rpm *= -1.0f;
257 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400258 vesc_set_rpm(2, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700259 }
260
261 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400262 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700263 if (flip) {
264 rpm *= -1.0f;
265 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400266 vesc_set_rpm(3, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700267 }
268 }
269
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700270 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400271 const float value = convert_input_width(4);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700272
273 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400274 float rpm = ::std::min(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700275 if (flip) {
276 rpm *= -1.0f;
277 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400278 vesc_set_rpm(4, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700279 }
280
281 {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400282 float rpm = ::std::max(0.0f, value) * kMaxRpm;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700283 if (flip) {
284 rpm *= -1.0f;
285 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400286 vesc_set_rpm(5, rpm);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700287 }
288 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400289 // Give the CAN frames a chance to go out.
290 delay(5);
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700291 }
292}
293
294void SetupPwmFtm(BigFTM *ftm) {
295 ftm->MODE = FTM_MODE_WPDIS;
296 ftm->MODE = FTM_MODE_WPDIS | FTM_MODE_FTMEN;
297 ftm->SC = FTM_SC_CLKS(0) /* Disable counting for now */;
298
299 // Can't change MOD according to the reference manual ("The Dual Edge Capture
300 // mode must be used with ... the FTM counter in Free running counter.").
301 ftm->MOD = 0xFFFF;
302
303 // Capturing rising edge.
304 ftm->C0SC = FTM_CSC_MSA | FTM_CSC_ELSA;
305 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400306 ftm->C1SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700307
308 // Capturing rising edge.
309 ftm->C2SC = FTM_CSC_MSA | FTM_CSC_ELSA;
310 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400311 ftm->C3SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700312
313 // Capturing rising edge.
314 ftm->C4SC = FTM_CSC_MSA | FTM_CSC_ELSA;
315 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400316 ftm->C5SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700317
318 // Capturing rising edge.
319 ftm->C6SC = FTM_CSC_MSA | FTM_CSC_ELSA;
320 // Capturing falling edge.
Brian Silvermana3a172b2018-03-24 03:53:32 -0400321 ftm->C7SC = FTM_CSC_CHIE | FTM_CSC_MSA | FTM_CSC_ELSB;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700322
Brian Silvermana3a172b2018-03-24 03:53:32 -0400323 (void)ftm->STATUS;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700324 ftm->STATUS = 0x00;
325
326 ftm->COMBINE = FTM_COMBINE_DECAP3 | FTM_COMBINE_DECAPEN3 |
327 FTM_COMBINE_DECAP2 | FTM_COMBINE_DECAPEN2 |
328 FTM_COMBINE_DECAP1 | FTM_COMBINE_DECAPEN1 |
329 FTM_COMBINE_DECAP0 | FTM_COMBINE_DECAPEN0;
330
331 // 34.95ms max period before it starts wrapping and being weird.
332 ftm->SC = FTM_SC_CLKS(1) /* Use the system clock */ |
333 FTM_SC_PS(4) /* Prescaler=32 */;
334
335 ftm->MODE &= ~FTM_MODE_WPDIS;
336}
337
Brian Silverman2de95d62018-03-31 12:32:24 -0700338struct AccelerometerResult {
339 uint16_t result;
340 bool success;
341};
342
343// Does a transfer on the accelerometer. Returns the resulting frame, or a
344// failure if it takes until after end_micros.
345AccelerometerResult AccelerometerTransfer(uint16_t data, uint32_t end_micros) {
346 SPI0_SR = SPI_SR_RFDF;
347 SPI0_PUSHR = SPI_PUSHR_PCS(1) | data;
348
349 while (!(SPI0_SR & SPI_SR_RFDF)) {
350 if (time_after(micros(), end_micros)) {
351 return {0, false};
352 }
353 }
354 const uint32_t popr = SPI0_POPR;
355 SPI0_SR = SPI_SR_RFDF;
356 return {static_cast<uint16_t>(popr & 0xFFFF), true};
357}
358
359constexpr uint32_t kAccelerometerTimeout = 500;
360
361bool AccelerometerWrite(uint8_t address, uint8_t data, uint32_t end_micros) {
362 const AccelerometerResult r = AccelerometerTransfer(
363 (static_cast<uint16_t>(address) << 8) | static_cast<uint16_t>(data),
364 end_micros);
365 return r.success;
366}
367
368AccelerometerResult AccelerometerRead(uint8_t address, uint32_t end_micros) {
369 AccelerometerResult r = AccelerometerTransfer(
370 (static_cast<uint16_t>(address) << 8) | UINT16_C(0x8000), end_micros);
371 r.result = r.result & UINT16_C(0xFF);
372 return r;
373}
374
375bool accelerometer_inited = false;
376
377void AccelerometerInit() {
378 accelerometer_inited = false;
379 const uint32_t end_micros = time_add(micros(), kAccelerometerTimeout);
380 {
381 const auto who_am_i = AccelerometerRead(0xF, end_micros);
382 if (!who_am_i.success) {
383 return;
384 }
385 if (who_am_i.result != 0x32) {
386 return;
387 }
388 }
Philipp Schrader790cb542023-07-05 21:06:52 -0700389 if (!AccelerometerWrite(0x20,
390 (1 << 5) /* Normal mode */ | (1 << 3) /* 100 Hz */ |
391 (1 << 2) /* Z enabled */ |
392 (1 << 1) /* Y enabled */ |
393 (1 << 0) /* X enabled */,
394 end_micros)) {
Brian Silverman2de95d62018-03-31 12:32:24 -0700395 }
396 // If want to read LSB, need to enable BDU to avoid splitting reads.
Philipp Schrader790cb542023-07-05 21:06:52 -0700397 if (!AccelerometerWrite(0x23,
398 (0 << 6) /* Data LSB at lower address */ |
399 (3 << 4) /* 400g full scale */ |
400 (0 << 0) /* 4-wire interface */,
Brian Silverman2de95d62018-03-31 12:32:24 -0700401 end_micros)) {
402 }
403 accelerometer_inited = true;
404}
405
406float AccelerometerConvert(uint16_t value) {
407 return static_cast<float>(400.0 / 65536.0) * static_cast<float>(value);
408}
409
410// Returns the total acceleration (in any direction) or 0 if there's an error.
411float ReadAccelerometer() {
412 if (!accelerometer_inited) {
413 AccelerometerInit();
414 return 0;
415 }
416
417 const uint32_t end_micros = time_add(micros(), kAccelerometerTimeout);
418 const auto x = AccelerometerRead(0x29, end_micros);
419 const auto y = AccelerometerRead(0x2B, end_micros);
420 const auto z = AccelerometerRead(0x2D, end_micros);
421 if (!x.success || !y.success || !z.success) {
422 accelerometer_inited = false;
423 return 0;
424 }
425
426 const float x_g = AccelerometerConvert(x.result);
427 const float y_g = AccelerometerConvert(y.result);
428 const float z_g = AccelerometerConvert(z.result);
429 return ::std::sqrt(x_g * x_g + y_g * y_g + z_g * z_g);
430}
431
Brian Silvermana3a172b2018-03-24 03:53:32 -0400432extern "C" void ftm0_isr() {
433 while (true) {
434 const uint32_t status = FTM0->STATUS;
435 if (status == 0) {
436 return;
437 }
438
439 if (status & (1 << 1)) {
440 const uint32_t start = FTM0->C0V;
441 const uint32_t end = FTM0->C1V;
442 pwm_input_widths[0] = (end - start) & 0xFFFF;
443 pwm_input_times[0] = millis();
444 }
445 if (status & (1 << 7)) {
446 const uint32_t start = FTM0->C6V;
447 const uint32_t end = FTM0->C7V;
448 pwm_input_widths[1] = (end - start) & 0xFFFF;
449 pwm_input_times[1] = millis();
450 }
451 if (status & (1 << 5)) {
452 const uint32_t start = FTM0->C4V;
453 const uint32_t end = FTM0->C5V;
454 pwm_input_widths[2] = (end - start) & 0xFFFF;
455 pwm_input_times[2] = millis();
456 }
457 if (status & (1 << 3)) {
458 const uint32_t start = FTM0->C2V;
459 const uint32_t end = FTM0->C3V;
460 pwm_input_widths[4] = (end - start) & 0xFFFF;
461 pwm_input_times[4] = millis();
462 }
463
464 FTM0->STATUS = 0;
465 }
466}
467
468extern "C" void ftm3_isr() {
469 while (true) {
470 const uint32_t status = FTM3->STATUS;
471 if (status == 0) {
472 return;
473 }
474
475 if (status & (1 << 3)) {
476 const uint32_t start = FTM3->C2V;
477 const uint32_t end = FTM3->C3V;
478 pwm_input_widths[3] = (end - start) & 0xFFFF;
479 pwm_input_times[3] = millis();
480 }
Brian Silverman7f5f1442018-04-06 13:00:50 -0400481 if (status & (1 << 7)) {
482 const uint32_t start = FTM3->C6V;
483 const uint32_t end = FTM3->C7V;
484 pwm_input_widths[5] = (end - start) & 0xFFFF;
485 pwm_input_times[5] = millis();
486 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400487
488 FTM3->STATUS = 0;
489 }
490}
491
492float ConvertEncoderChannel(uint16_t reading) {
493 // Theoretical values based on the datasheet are 931 and 2917.
494 // With these values, the magnitude ranges from 0.99-1.03, which works fine
495 // (the encoder's output appears to get less accurate in one quadrant for some
496 // reason, hence the variation).
497 static constexpr uint16_t kMin = 802, kMax = 3088;
498 if (reading < kMin) {
499 reading = kMin;
500 } else if (reading > kMax) {
501 reading = kMax;
502 }
503 return (static_cast<float>(2 * (reading - kMin)) /
504 static_cast<float>(kMax - kMin)) -
505 1.0f;
506}
507
508struct EncoderReading {
Brian Silvermana96c1a42018-05-12 12:11:31 -0700509 EncoderReading(const SimpleAdcReadings &adc_readings) {
Brian Silvermana3a172b2018-03-24 03:53:32 -0400510 const float sin = ConvertEncoderChannel(adc_readings.sin);
511 const float cos = ConvertEncoderChannel(adc_readings.cos);
512
Austin Schuhbcce26a2018-03-26 23:41:24 -0700513 const float magnitude = hypot(sin, cos);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400514 const float magnitude_error = ::std::abs(magnitude - 1.0f);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700515 valid = magnitude_error < 0.30f;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400516
517 angle = ::std::atan2(sin, cos);
518 }
519
520 // Angle in radians, in [-pi, pi].
521 float angle;
522
523 bool valid;
524};
525
526extern "C" void pit3_isr() {
527 PIT_TFLG3 = 1;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700528 PolyDrivetrain<float> *polydrivetrain =
529 global_polydrivetrain.load(::std::memory_order_acquire);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700530 Spring *spring = global_spring.load(::std::memory_order_acquire);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400531
Brian Silvermana96c1a42018-05-12 12:11:31 -0700532 SimpleAdcReadings adc_readings;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400533 {
534 DisableInterrupts disable_interrupts;
Brian Silvermana96c1a42018-05-12 12:11:31 -0700535 adc_readings = AdcReadSimple(disable_interrupts);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400536 }
537
538 EncoderReading encoder(adc_readings);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700539 static float last_good_encoder = 0.0f;
540 static int invalid_encoder_count = 0;
541 if (encoder.valid) {
542 last_good_encoder = encoder.angle;
543 invalid_encoder_count = 0;
544 } else {
545 ++invalid_encoder_count;
546 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400547
Austin Schuhe666dc62018-08-08 21:09:12 -0700548 const bool lost_spring_channel = lost_channel(2) || lost_channel(3) ||
549 lost_channel(4) || lost_channel(5) ||
550 (convert_input_width(4) < 0.5f);
551
552 const bool lost_drive_channel = lost_channel(0) || lost_channel(1) ||
553 (::std::abs(convert_input_width(4)) < 0.5f);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700554
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700555 if (polydrivetrain != nullptr && spring != nullptr) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556 float throttle;
557 float wheel;
Austin Schuhe666dc62018-08-08 21:09:12 -0700558 if (lost_drive_channel) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559 throttle = 0.0f;
560 wheel = 0.0f;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700561 } else {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562 throttle = convert_input_width(1);
563 wheel = -convert_input_width(0);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700564 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565 const bool quickturn = ::std::abs(polydrivetrain->velocity()) < 0.25f;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700566
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 OutputT output;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700568
Alex Perrycb7da4b2019-08-28 19:35:56 -0700569 polydrivetrain->SetGoal(wheel, throttle, quickturn, false);
Austin Schuheeec74a2019-01-27 20:58:59 -0800570 polydrivetrain->Update(12.0f);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700571 polydrivetrain->SetOutput(&output);
572
573 vesc_set_duty(0, -output.left_voltage / 12.0f);
574 vesc_set_duty(1, -output.left_voltage / 12.0f);
575
576 vesc_set_duty(2, output.right_voltage / 12.0f);
577 vesc_set_duty(3, output.right_voltage / 12.0f);
578
Austin Schuhe666dc62018-08-08 21:09:12 -0700579 const bool prime = convert_input_width(2) > 0.1f;
580 const bool fire = convert_input_width(3) > 0.1f;
581 const bool force_move =
582 (convert_input_width(5) > 0.1f) && !lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700583
Austin Schuhe666dc62018-08-08 21:09:12 -0700584 bool unload = lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700585 static bool was_lost = true;
Austin Schuhe666dc62018-08-08 21:09:12 -0700586 bool force_reset = !lost_spring_channel && was_lost;
587 was_lost = lost_spring_channel;
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700588
Austin Schuhe666dc62018-08-08 21:09:12 -0700589 spring->Iterate(unload, prime, fire, force_reset, force_move,
590 invalid_encoder_count <= 2, last_good_encoder);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700591
592 float spring_output = spring->output();
593
594 vesc_set_duty(4, -spring_output);
595 vesc_set_duty(5, spring_output);
596
Brian Silverman2de95d62018-03-31 12:32:24 -0700597 const float accelerometer = ReadAccelerometer();
598 (void)accelerometer;
599
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700600 /*
601 // Massive debug. Turn on for useful bits.
Brian Silverman2de95d62018-03-31 12:32:24 -0700602 printf("acc %d/1000\n", (int)(accelerometer / 1000));
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700603 if (!encoder.valid) {
604 printf("Stuck encoder: ADC %" PRIu16 " %" PRIu16
605 " enc %d/1000 %s mag %d\n",
606 adc_readings.sin, adc_readings.cos, (int)(encoder.angle * 1000),
607 encoder.valid ? "T" : "f",
608 (int)(hypot(ConvertEncoderChannel(adc_readings.sin),
609 ConvertEncoderChannel(adc_readings.cos)) *
610 1000));
611 }
Austin Schuhbcce26a2018-03-26 23:41:24 -0700612 static int i = 0;
613 ++i;
614 if (i > 20) {
615 i = 0;
Austin Schuhe666dc62018-08-08 21:09:12 -0700616 if (lost_spring_channel || lost_drive_channel) {
617 printf("200Hz loop, disabled %d %d %d %d %d %d\n",
Austin Schuhbcce26a2018-03-26 23:41:24 -0700618 (int)(convert_input_width(0) * 1000),
619 (int)(convert_input_width(1) * 1000),
620 (int)(convert_input_width(2) * 1000),
621 (int)(convert_input_width(3) * 1000),
Austin Schuhe666dc62018-08-08 21:09:12 -0700622 (int)(convert_input_width(4) * 1000),
623 (int)(convert_input_width(5) * 1000));
Austin Schuhbcce26a2018-03-26 23:41:24 -0700624 } else {
625 printf(
Austin Schuhe666dc62018-08-08 21:09:12 -0700626 "TODO(Austin): 200Hz loop %d %d %d %d %d %d, lr, %d, %d velocity %d
627 "
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700628 " state: %d, near %d angle %d goal %d to: %d ADC %" PRIu16
629 " %" PRIu16 " enc %d/1000 %s from %d\n",
Austin Schuhbcce26a2018-03-26 23:41:24 -0700630 (int)(convert_input_width(0) * 1000),
631 (int)(convert_input_width(1) * 1000),
632 (int)(convert_input_width(2) * 1000),
633 (int)(convert_input_width(3) * 1000),
634 (int)(convert_input_width(4) * 1000),
Austin Schuhe666dc62018-08-08 21:09:12 -0700635 (int)(convert_input_width(5) * 1000),
Austin Schuhbcce26a2018-03-26 23:41:24 -0700636 static_cast<int>(output.left_voltage * 100),
637 static_cast<int>(output.right_voltage * 100),
638 static_cast<int>(polydrivetrain->velocity() * 100),
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700639 static_cast<int>(spring->state()), static_cast<int>(spring->Near()),
640 static_cast<int>(spring->angle() * 1000),
641 static_cast<int>(spring->goal() * 1000),
642 static_cast<int>(spring->timeout()), adc_readings.sin,
643 adc_readings.cos, (int)(encoder.angle * 1000),
Austin Schuhbcce26a2018-03-26 23:41:24 -0700644 encoder.valid ? "T" : "f",
645 (int)(::std::sqrt(ConvertEncoderChannel(adc_readings.sin) *
646 ConvertEncoderChannel(adc_readings.sin) +
647 ConvertEncoderChannel(adc_readings.cos) *
648 ConvertEncoderChannel(adc_readings.cos)) *
649 1000));
650 }
651 }
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700652 */
Austin Schuhbcce26a2018-03-26 23:41:24 -0700653 }
Brian Silvermana3a172b2018-03-24 03:53:32 -0400654}
655
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700656} // namespace
657
658extern "C" {
659
660void *__stack_chk_guard = (void *)0x67111971;
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700661void __stack_chk_fail(void);
662
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700663} // extern "C"
664
665extern "C" int main(void) {
666 // for background about this startup delay, please see these conversations
667 // https://forum.pjrc.com/threads/36606-startup-time-(400ms)?p=113980&viewfull=1#post113980
668 // https://forum.pjrc.com/threads/31290-Teensey-3-2-Teensey-Loader-1-24-Issues?p=87273&viewfull=1#post87273
669 delay(400);
670
671 // Set all interrupts to the second-lowest priority to start with.
672 for (int i = 0; i < NVIC_NUM_INTERRUPTS; i++) NVIC_SET_SANE_PRIORITY(i, 0xD);
673
674 // Now set priorities for all the ones we care about. They only have meaning
675 // relative to each other, which means centralizing them here makes it a lot
676 // more manageable.
677 NVIC_SET_SANE_PRIORITY(IRQ_USBOTG, 0x7);
Brian Silvermana3a172b2018-03-24 03:53:32 -0400678 NVIC_SET_SANE_PRIORITY(IRQ_FTM0, 0xa);
679 NVIC_SET_SANE_PRIORITY(IRQ_FTM3, 0xa);
680 NVIC_SET_SANE_PRIORITY(IRQ_PIT_CH3, 0x5);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700681
682 // Builtin LED.
683 PERIPHERAL_BITBAND(GPIOC_PDOR, 5) = 1;
684 PORTC_PCR5 = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(1);
685 PERIPHERAL_BITBAND(GPIOC_PDDR, 5) = 1;
686
687 // Set up the CAN pins.
688 PORTA_PCR12 = PORT_PCR_DSE | PORT_PCR_MUX(2);
689 PORTA_PCR13 = PORT_PCR_DSE | PORT_PCR_MUX(2);
690
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700691 // PWM_IN0
692 // FTM0_CH0
693 PORTC_PCR1 = PORT_PCR_MUX(4);
694
695 // PWM_IN1
696 // FTM0_CH6
697 PORTD_PCR6 = PORT_PCR_MUX(4);
698
699 // PWM_IN2
700 // FTM0_CH4
701 PORTD_PCR4 = PORT_PCR_MUX(4);
702
703 // PWM_IN3
704 // FTM3_CH2
705 PORTD_PCR2 = PORT_PCR_MUX(4);
706
707 // PWM_IN4
708 // FTM0_CH2
709 PORTC_PCR3 = PORT_PCR_MUX(4);
710
Brian Silverman7f5f1442018-04-06 13:00:50 -0400711 // PWM_IN5
712 // FTM3_CH6
713 PORTC_PCR10 = PORT_PCR_MUX(3);
714
Brian Silverman2de95d62018-03-31 12:32:24 -0700715 // SPI0
716 // ACC_CS PCS0
717 PORTA_PCR14 = PORT_PCR_DSE | PORT_PCR_MUX(2);
718 // SCK
719 PORTA_PCR15 = PORT_PCR_DSE | PORT_PCR_MUX(2);
720 // MOSI
721 PORTA_PCR16 = PORT_PCR_DSE | PORT_PCR_MUX(2);
722 // MISO
723 PORTA_PCR17 = PORT_PCR_DSE | PORT_PCR_MUX(2);
724
725 SIM_SCGC6 |= SIM_SCGC6_SPI0;
726 SPI0_MCR = SPI_MCR_MSTR | SPI_MCR_PCSIS(1) | SPI_MCR_CLR_TXF |
727 SPI_MCR_CLR_RXF | SPI_MCR_HALT;
728 // 60 MHz "protocol clock"
729 // 6ns CS setup
730 // 8ns CS hold
731 SPI0_CTAR0 = SPI_CTAR_FMSZ(15) | SPI_CTAR_CPOL /* Clock idles high */ |
732 SPI_CTAR_CPHA /* Data captured on trailing edge */ |
733 0 /* !LSBFE MSB first */ |
734 SPI_CTAR_PCSSCK(0) /* PCS->SCK prescaler = 1 */ |
735 SPI_CTAR_PASC(0) /* SCK->PCS prescaler = 1 */ |
736 SPI_CTAR_PDT(0) /* PCS->PCS prescaler = 1 */ |
737 SPI_CTAR_PBR(0) /* baud prescaler = 1 */ |
738 SPI_CTAR_CSSCK(0) /* PCS->SCK 2/60MHz = 33.33ns */ |
739 SPI_CTAR_ASC(0) /* SCK->PCS 2/60MHz = 33.33ns */ |
740 SPI_CTAR_DT(2) /* PCS->PSC 8/60MHz = 133.33ns */ |
741 SPI_CTAR_BR(2) /* BR 60MHz/6 = 10MHz */;
742
743 SPI0_MCR &= ~SPI_MCR_HALT;
744
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700745 delay(100);
746
Brian Silverman4787a6e2018-10-06 16:00:54 -0700747 PrintingParameters printing_parameters;
748 printing_parameters.dedicated_usb = true;
749 const ::std::unique_ptr<PrintingImplementation> printing =
750 CreatePrinting(printing_parameters);
751 printing->Initialize();
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700752
Brian Silvermana3a172b2018-03-24 03:53:32 -0400753 SIM_SCGC6 |= SIM_SCGC6_PIT;
754 // Workaround for errata e7914.
755 (void)PIT_MCR;
756 PIT_MCR = 0;
Austin Schuhbcce26a2018-03-26 23:41:24 -0700757 PIT_LDVAL3 = (BUS_CLOCK_FREQUENCY / 200) - 1;
Brian Silvermana3a172b2018-03-24 03:53:32 -0400758 PIT_TCTRL3 = PIT_TCTRL_TIE | PIT_TCTRL_TEN;
759
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700760 can_init(0, 1);
Brian Silvermana96c1a42018-05-12 12:11:31 -0700761 AdcInitSimple();
Brian Silverman4f8c6a72018-03-17 23:12:45 -0700762 SetupPwmFtm(FTM0);
763 SetupPwmFtm(FTM3);
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700764
Austin Schuhbcce26a2018-03-26 23:41:24 -0700765 PolyDrivetrain<float> polydrivetrain(GetDrivetrainConfig(), nullptr);
766 global_polydrivetrain.store(&polydrivetrain, ::std::memory_order_release);
Austin Schuh4fae0fc2018-03-27 23:51:42 -0700767 Spring spring;
768 global_spring.store(&spring, ::std::memory_order_release);
Austin Schuhbcce26a2018-03-26 23:41:24 -0700769
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700770 // Leave the LEDs on for a bit longer.
771 delay(300);
772 printf("Done starting up\n");
773
Brian Silverman2de95d62018-03-31 12:32:24 -0700774 AccelerometerInit();
775 printf("Accelerometer init %s\n", accelerometer_inited ? "success" : "fail");
776
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700777 // Done starting up, now turn the LED off.
778 PERIPHERAL_BITBAND(GPIOC_PDOR, 5) = 0;
779
Brian Silvermana3a172b2018-03-24 03:53:32 -0400780 NVIC_ENABLE_IRQ(IRQ_FTM0);
781 NVIC_ENABLE_IRQ(IRQ_FTM3);
782 NVIC_ENABLE_IRQ(IRQ_PIT_CH3);
Austin Schuhe666dc62018-08-08 21:09:12 -0700783 printf("Done starting up2\n");
Brian Silvermana3a172b2018-03-24 03:53:32 -0400784
Philipp Schrader790cb542023-07-05 21:06:52 -0700785 // DoReceiverTest2();
Austin Schuhbcce26a2018-03-26 23:41:24 -0700786 while (true) {
787 }
Brian Silverman54dd2fe2018-03-16 23:44:31 -0700788
789 return 0;
790}
791
792void __stack_chk_fail(void) {
793 while (true) {
794 GPIOC_PSOR = (1 << 5);
795 printf("Stack corruption detected\n");
796 delay(1000);
797 GPIOC_PCOR = (1 << 5);
798 delay(1000);
799 }
800}
801
802} // namespace motors
803} // namespace frc971